Important of Encapsulation in java
Important of Encapsulation in java
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.
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; }
public int getAge() // get method for age to access private variable Age
{
return Age;
}
}
}
}
Output:
Geek's name: Harish
Geek's age: 19
Geek's roll: 51
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)
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.
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)
{
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 {
Introduction:
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
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.
Example Program:
package p1;
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();
}
}
a class to a package.
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:
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