Encapsulation in java

Encapsulation
Binding data and code together into a single unit is known as encapsulation.
Java class is the best example of encapsulation.

For example, programmer are writing employee and student classes with same variables id and name. Also they can write same method display in both classes. It is possible to store different data in the variables. The data of one class will not spoil of another class.

Example
class employee
{
int id = 1;
String name=”Jimmy”;
void display()
{
System.out.println(“id= “+id);
System.out.println(“name= “+name);
}
}
class student
{
int id = 11;
String name=”Adam”;
void display()
{
System.out.println(“id= “+id);
System.out.println(“name= “+name);
}
}

Leave a Reply

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