Home » Core Java » Encapsulation in Java

Encapsulation in Java


Encapsulation is another OOPS concept which allows objects to hide the details and present only essentials.private access modifier is used to hide details and protected or public or default access modifiers are used to present essentials.Like a capsule where the medicine inside it, is hidden from outside,a private variable is hidden inside the class and not visible to outside.

Example :

Since we have declared amount as private,if a hacker wants to change the amount to negative value using object class ,one will get compile time exception.The smart programmer can also put some conditional check like amount is less than 0 ,then return same input amount.

Advantages of Encapsulation :
1 : Class can be made read only by providing only getter method and write only by providing only setter method.
2 : Class can have full control of its variables and make it safe from hacker.

Leave a comment

Your email address will not be published. Required fields are marked *

5 × 4 =