Java Programming
Topperworld.in
encapsulation in java
Encapsulation in Java refers to integrating data (variables) and code
(methods) into a single unit. In encapsulation, a class's variables are hidden
from other classes and can only be accessed by the methods of the class in
which they are found.
Example of Data Encapsulation
Below is a program to calculate the perimeter of a rectangle:
©Topperworld
Java Programming
©Topperworld
Output:
❖ Data Hiding
Access modifiers are used to achieve data hiding. Access modifiers are the
keywords that specify the accessibility or the scope of methods, classes,
fields, and other members.
Difference between encapsulation and data hiding is that Encapsulation is a
way of bundling data whereas Data Hiding prevents external unauthorized
access to the sensitive data.
The four types of access modifiers in Java are:
• Public: A public modifier is accessible to everyone. It can be accessed
from within the class, outside the class, within the package, and outside
the package.
• Private: A private modifier can not be accessed outside the class. It
provides restricted access. Example:
©Topperworld
Java Programming
©Topperworld
• Protected: A protected modifier can be accessed from the classes of the
same package and outside the package only through inheritance.
• Default: A default modifier is accessible only within the package. If no
modifier is used, it is treated as default.
Or,
©Topperworld
Java Programming
©Topperworld
Example of Data Hiding:
Output:
©Topperworld
Java Programming
❖ How to implement Encapsulation in Java?
We need to perform two steps to achieve the purpose of Encapsulation in
Java.
• Use the private access modifier to declare all variables/fields of class
as private.
• Define public getter and setter methods to read and modify/set the
values of the abovesaid fields.
Example:
©Topperworld
Java Programming
©Topperworld
Output:
©Topperworld
Java Programming
©Topperworld
❖ Benefits of Encapsulation java
• Cleaner, more organized and less complex code.
• More flexible code as can modify a unit independently without
changing any other unit.
• Makes the code more secure.
• The code can be maintained at any point without breaking the classes
that use the code.
©Topperworld