Object-oriented programming for Java - 7

Java Encapsulation

 

 


1. Java Encapsulation

Encapsulation refers to the bundling of fields and methods inside a single class.

It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data hiding.

Example: (just Encapsulation, no data hiding)

 

2. Data Hiding in Java Encapsulation

use access modifiers (Like: private specifier) to achieve data hiding.

Example: (Data hiding using the private specifier)

P.S.

In this example, the age varible can't access directly like:

Because the age is private method, and this is unauthorized access.