Encapsulation
Encapsulation
Process of binding object state(fields) and behaviors(methods) together in a single entity called “Class”.
Encapsulation wraps both fields and methods in a class, It will be secured from the outside access.
We can restrict the access to the members of a class using access modifiers along with encapsulation.
When we create a class in Java, It means we are doing encapsulation.
Encapsulation helps us to achieve the reusability of code without compromising the security.
Example
We create a class and write a method to add 2 numbers.
Now , Addition logic can be accessed by other class if they also need to add 2 numbers rather than writing the whole logic again.
In this scenario , we can keep fields of our class as private
and make add() method as public
So that other classes can access only the logic and can’t access the private
fields and hence our data will be secured.
This way they are able to reuse the existing Add numbers logic.
Let’s see the example program for the same
ArithmeticOperation.java
- Class ArithmeticOperation{
- Private Int a=10;
- Private Int b=20;
- Public int add(int p,int q){
- return p+q;
- }
- }
Class ArithmeticOperation{ Private Int a=10; Private Int b=20; Public int add(int p,int q){ return p+q; } }
AverageFinder.java
- Class AverageFinder{
- public static void main(String args[]){
- ArithmeticOperation obj = new ArithmeticOperation();
- int x=30;
- int y=20;
- int sum = obj.add(x,y);
- int avg = sum / 2;
- System.out.println(“Average = "+avg);
- }
- }
Class AverageFinder{ public static void main(String args[]){ ArithmeticOperation obj = new ArithmeticOperation(); int x=30; int y=20; int sum = obj.add(x,y); int avg = sum / 2; System.out.println(“Average = "+avg); } }
We can see that , AverageFinder class is reusing the addition logic encapsulated inside ArithmeticOperation class.
The fields declared inside ArithmeticOperation(both a and b) are secured as we declared those fields as private
.