0% found this document useful (0 votes)
5 views

Important of Encapsulation in java

The document discusses encapsulation in Java, highlighting its importance in object-oriented programming by binding data with methods and improving data security and flexibility. It explains the need for encapsulation, its benefits, and provides examples of how to implement it using getter and setter methods. Additionally, it introduces the Single Responsibility Principle (SRP) as part of the SOLID principles, emphasizing that a class should have only one responsibility to enhance maintainability and testability.

Uploaded by

talikotimuttu2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Important of Encapsulation in java

The document discusses encapsulation in Java, highlighting its importance in object-oriented programming by binding data with methods and improving data security and flexibility. It explains the need for encapsulation, its benefits, and provides examples of how to implement it using getter and setter methods. Additionally, it introduces the Single Responsibility Principle (SRP) as part of the SOLID principles, emphasizing that a class should have only one responsibility to enhance maintainability and testability.

Uploaded by

talikotimuttu2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

OOP and Design with Java 20CS43P

Week-6: Encapsulation in Java


What is Encapsulation in Java?

 Encapsulation is one important feature of OOPs.


 Encapsulation means Binding data with methods.
 Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
 Encapsulation in Java is a powerful mechanism for storing the data members and data methods of
a class together.
 In encapsulation, the data members and data methods of a class is hidden from any other class
and can be accessed only through any member function of its own class in which it is declared.
 Encapsulation can be achieved by declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.
 It is more defined with setter and getter method.
 Encapsulation is about combining methods with data members.
 The main motto is to combine data and their methods.

Need for Encapsulation in Java


 Encapsulation improves the procedure of coding. We need encapsulation in Java for various
reasons. They are stated below

 Better Control: Encapsulation provides ultimate control over the data members and data methods
inside the class.
 Getter and Setter: The standard IDEs provide in-built support for ‘Getter and Setter’ methods,
which increases the programming pace.
 Security: Encapsulation prevents access to data members and data methods by any external classes.
The encapsulation process improves the security of the encapsulated data.
 Flexibility: Changes made to one part of the code can be successfully implemented without
affecting any other part of the code.

[GPT Athani-CSE] Page 1


OOP and Design with Java 20CS43P

Benefits of Encapsulation in Java


 A class can have complete control over its data members and data methods.
 The class will maintain its data members and methods as read-only.
 Data hiding prevents the user from the complex implementations in the code.
 The variables of the class can be read-only or write-only as per the programmer's requirement.
 Encapsulation in Java provides an option of code-reusability.
 Using encapsulation will help in making changes to an existing code quickly.
 Unit testing a code designed using encapsulation is elementary.
 Standard IDEs have the support of getters and setters; this makes coding even faster.

Encapsulation in Java can be achieved by:


 Declaring the variables of a class as private.
 Providing public setter and getter methods to modify and view the variables values.

The program to access variables of the class EncapsulationDemo is shown below:

// Java program to demonstrate encapsulation

class Encapsulate

{
// private variables declared these can only be accessed by public methods of class
private String Name;
private int Roll;
private int Age;

public void setAge(int newAge) // set method for age to access private variable age
{
Age = newAge;
}
public void setName(String newName) // set method for name to access private variable Name
{
Name = newName;
}
public void setRoll(int newRoll) // set method for roll to access private variable Roll
{
Roll = newRoll;
}
public String getName() // get method for name to access private variable Name
{
return Name;
}

public int getRoll() // get method for roll to access private variable Roll
{
return Roll; }

[GPT Athani-CSE] Page 2


OOP and Design with Java 20CS43P

public int getAge() // get method for age to access private variable Age
{
return Age;
}
}

public class EncapsulationDemo {


public static void main(String[] args)
{
Encapsulate obj = new Encapsulate(); // Creating object
// setting values of the variables using set methods
obj.setName("Harish");
obj.setAge(19);
obj.setRoll(51);
// Displaying values of the variables using get methods
System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());
System.out.println("Geek's roll: " + obj.getRoll());

// Direct access of geekRoll is not possible due to encapsulation

// System.out.println("Geek's roll: " + obj.Name); // Not possible

}
}
Output:
Geek's name: Harish
Geek's age: 19
Geek's roll: 51

Single Responsibility Principle: Intent; Rules; Benefits; example

 In software development, Object-Oriented Design plays a crucial role when it comes to writing
flexible, scalable, maintainable, and reusable code. There are so many benefits of using OOD but
every developer should also have the knowledge of the SOLID principle for good object-
oriented design in programming.
 The SOLID principle was introduced by Robert C. Martin, popularly known as Uncle Bob and it
is a coding standard in programming. This principle is an acronym of the five principles which is
given below…
1. Single Responsibility Principle (SRP)
2. Open/Closed Principle(OCP)
3. Liskov’s Substitution Principle (LSP)
4. Interface Segregation Principle (ISP)
5. Dependency Inversion Principle (DIP)

[GPT Athani-CSE] Page 3


OOP and Design with Java 20CS43P

Single Responsibility Principle (SRP):


SRP stands for the Single Responsibility Principle, which is one of the five SOLID principles of object-
oriented programming (OOP). It was introduced by Robert C. Martin (also known as Uncle Bob). The
principle emphasizes that a class should have only one reason to change, meaning it should have only
one responsibility or job.

Definition of SRP
A class should have only one reason to change, meaning it should have only one responsibility
or job.A class should focus on doing one thing and do it well. If a class has multiple responsibilities, it
becomes harder to maintain, test, and understand.

Why SRP is Important??


Maintainability: Classes with a single responsibility are easier to understand, modify, and debug.

Reusability: Smaller, focused classes are more likely to be reusable in different contexts.

Testability: Classes with a single responsibility are easier to test because they have fewer behaviors to
verify.

Reduced Coupling: By separating responsibilities, you reduce dependencies between classes, making
the system more modular.

Easier Refactoring: When a class has only one responsibility, changes to that responsibility are
isolated, reducing the risk of introducing bugs.

Example:
Define a java class for a Simple Calculator and check this class compliance with Single
Responsibility Principle (SRP).
Solution:
Program: Java Program to implement the solution for the given problem.
class Calculator
{
// this class is responsible for Arithmetic operations and printing Values
public static int add(int x, int y)
{
return x + y;
}
public static int sub(int x, int y)
{
return x - y;
}
public static int mul(int x, int y)
{

[GPT Athani-CSE] Page 4


OOP and Design with Java 20CS43P

return x * y;
}
public static int div(int x, int y)
{
return x / y;
}
public static void display(int value)
{
System.out.println("The value is="+value);
}
}
class CalcNoSRP
{
public static void main(String args[])
{
int a = Calculator.add(20, 30);
Calculator.display(a);
int b = Calculator.sub(20, 30);
Calculator.display(b);
int c = Calculator.mul(20, 30);
Calculator.display(c);
int d = Calculator.div(20, 30);
Calculator.display(d);
}
}
/*The above program violates SRP, since the class Calculator has 2 responsibilities Arithmetic operations
and printing Values.To maintain SRP we have to write the program so that the class should have only one
responsibility.*/

class Calculator {

public static int add(int x, int y) {


return x + y;
}

public static int sub(int x, int y) {


return x - y;
}

public static int mul(int x, int y) {


return x * y;
}

[GPT Athani-CSE] Page 5


OOP and Design with Java 20CS43P

public static int div(int x, int y) {


return x / y;
}
}

class OutputDisplay { // Separate class for displaying output

public static void display(int value) {


System.out.println("The value is = " + value);
}
}
class SRPDemo{

public static void main(String args[]) {


int a = Calculator.add(20, 30);
OutputDisplay.display(a); // Use OutputDisplay to print
int b = Calculator.sub(20, 30);
OutputDisplay.display(b); // Use OutputDisplay to print
int c = Calculator.mul(20, 30);
OutputDisplay.display(c); // Use OutputDisplay to print
int d = Calculator.div(20, 30);
OutputDisplay.display(d); // Use OutputDisplay to print
}
}

PACKAGES: PUTTING CLASSES TOGETHER

Introduction:

Packages are Java’s way of grouping a variety of classes or interfaces together.


Packages act as “containers” for classes.
Packages allow us to use classes from other programs without physically copying them into the
program i.e reusability of code already created.
Purpose of Packages
 Organization: Group related classes and interfaces together.
 Avoid Naming Conflicts: Classes in different packages can have the same name.
 Access Control: Packages provide a way to control visibility using access modifiers
(public, protected, private, and default).
 Reusability: Packages can be reused across projects.

[GPT Athani-CSE] Page 6


OOP and Design with Java 20CS43P

Benefits of Packages:

 Organization: Packages group related classes and interfaces into a single unit, making it easier to
maintain a well-structured project.
 Naming Conflicts: They prevent naming conflicts by creating a new namespace, allowing classes
with the same name to exist in different packages.
 Access Control: Packages provide access protection, allowing control over which classes and
members are accessible from outside the package.
 Code Reusability: They facilitate code reuse by allowing existing classes in packages to be reused
in other programs.
 Easy Location: Packages make it simpler to locate related classes within a project.
 Distribution and Deployment: Packages make it easier to distribute and deploy Java applications
by bundling related classes and resources into modular units

Java packages are classified into two types:


1. JAVA API package or System package 2. User-defined package.
1. Built-in package or API package or System package:
 Java API provides a large number of classes grouped into different packages according to
functions. They are:
● java.lang
● java.util
● java.io
● java.net
● java.awt
● java.applet

Fig . Java API Package (Application Programming Interface Package)


i) java.lang (Language support package).
 This package contains essential java classes and interfaces that form the core of the java language
and JVM. This is the only package that is imported automatically into every java program.
 It includes classes for primitive types, strings, Thread, Exceptions, Errors and Math functions.
ii) java.util (Utility package)
 This package contains utility classes and related interfaces .These packages contains collection of
classes to provide utility functions such as date & time functions, classes that provide generic data
structures(stack, vector), string manipulation classes, system properties classes, notification classes.
iii)java.io (Input/output packages)

[GPT Athani-CSE] Page 7


OOP and Design with Java 20CS43P

 This package contains a collection of input/output support classes. To manage i/o streams for
reading and writing data to files, string, and other i/o devices sources.
 Example classes include FileInputStream, DataInputStream,DataOutputStream etc.
iv) java.net (Networking package)
 This networking package contains a collection of classes and interfaces establishing communication
with other computers over internet. Example classes include DatagramSocket, URL,
URL_connection etc.
v) java.awt (AWT package)
 The Abstract Window Toolkit package contains classes, which provides GUI (Graphical User
Interface) in java language. i.e. GUI elements such as buttons, text fields, radio buttons, check
boxes, combo boxes etc. Each GUI element is called an AWT component.
vi) java.applet (Applet package)
● This Applet package contains classes to create an applet used to communicate with its applet
context and set of classes that allow us to create java applet.
● Example: AppletContext, AppletStub, Applet etc.

Steps to create user defined package:


1. Choose a Package Name: Select a meaningful and unique name for your package. Conventionally,
package names are written in lowercase and follow the reverse domain name notation, such
as com.example.mypackage
2. Create a Directory Structure: In your file system, create a directory structure that matches your
package name. For example, if your package is named com.example.myapp, create a directory
structure like this: com/example/myapp.
3. Declare the Package: Include the package command as the first statement in each Java source file
that belongs to the package
For example: package com.example.mypackage; This statement specifies which package the classes
defined belong to.
4. Place Your Classes: Put the Java source files (.java files) within the directory structure that reflects
the package hierarchy. For example, the source file should be located
at com/example/mypackage/MyClass.java in the file system.
5. Compile and Use: Compile your Java code. You can then use the classes in your package by
importing the package in another class using the import statement.
For example: import com.example.mypackage.MyClass;

Example Program:
package p1;

public class Student


{
int regno;
String name;
public void setData(int r, String s)
{

[GPT Athani-CSE] Page 8


OOP and Design with Java 20CS43P

regno = r;
name = s;
}
public void putData()
{
System.out.println("regno = " + regno);
System.out.println("name = " + name);
}
}

import p1.*;

class StudentTest
{
public static void main(String args[])
{
Student s = new Student();
s.setData(179, "gpta");
s.putData();
}
}

Q) Define Package. Explain how to access package with an example.


 Java supports another reusability feature called “package”.
 A package is a group of related classes and interfaces together.
Accessing Package:
 The “import” keyword is used to access the built-in package and also user-defined package.
 The general form of import statement is-
import package1.[.package2][.package3].classname;
Here, package1- name of the top level package.
package2- name of the package inside package1 and so on.
classname-explicit classname
 A statement must end with a semicolon(;).
 The user can access the subpackage using dot(.) operator followed by main package.
Ex: import firstPackage.secondPackage.Myclass;
 We can also use another approach as follows.
import packagename.*; which imports all classes from package.
Q) Explain how to add class to a Package. OR Write a Java program to add

[GPT Athani-CSE] Page 9


OOP and Design with Java 20CS43P

a class to a package.

 It is simple to add a class to an existing package. Consider the following packages :


package p1;
public class A
{
// Body of class A
}
 The package p1 contains one public class by name A. Suppose we want to add another class B to
this package.
 This can be done as follows:
i. Define the class and make it public.
ii. Place the package statement
package p1;
before the class definition as follows:
package p1;
public class B
{
// body of B
}
iii. Store this as B.java file under the directory p1.
iv. Compile B.java file .This will create a B.class file and place it in the directory p1.
 Note that we can also add a non-public class to a package using same procedure.
 Now, the package p1 will contain both the classes A and B. A statement like
import p1.*; will import both of them.
Example Program:
package p1;

public class Student


{
int regno;
String name;

public void setData(int r, String s)


{
regno = r;
name = s;
}

public void putData()


{

[GPT Athani-CSE] Page 10


OOP and Design with Java 20CS43P

System.out.println("regno = " + regno);


System.out.println("name = " + name);
}
}

import p1.*;

class StudentTest
{
public static void main(String args[])
{
Student s = new Student();
s.setData(178, "gpta");
s.putData();
}
}

Hiding a class:
 When we import a package using asterisk (*), all public classes are imported.
 But we may prefer to “not import” certain classes. That is we may like to hide these classes from
accessing from outside of the packages.
 Such classes should be declared “not public”.
Example:
package p1;
public class X //public class, available outside
{
//body of x
}
class Y //not public, hidden
{
//body of Y
}
 Here, the class Y which is not declared public is hidden from outside the package.
 This class can be seen and used only by other classes in the same package.
 A java source file should contain only one public and may include any number of non public
classes.
 Now, consider the following code, which imports package p1 that contain classes X and Y:
import p1.*;
X objectX; //OK; class X is available here
Y objectY; //Not OK; Y is not available here
 Java compiler would generate an error message for this code because the class Y, which has not been
declared public, is not imported and therefore not available for creating its objects.
Visibility controls in Packages:

[GPT Athani-CSE] Page 11


OOP and Design with Java 20CS43P

 While using packages and inheritance in a program, we should be aware of the visibility restriction
imposed by various access protection modifiers. Access protection modifiers are-
i) Private ii) Protected iii) Public iv) default

[GPT Athani-CSE] Page 12

You might also like