Encapsulation
Encapsulation is defined as the process of combining the data and functions into one entity, encapsulation is a concept of making fields private and allow the access through public methods.
As we are making field private so it is also referred as data hiding.
Public methods which are created to set the private fields are known as setters.
Public methods which are created to read private fields value are known as getters.
Encapsulation provides a protective barrier for a fields which helps in preventing field from random access.
Example of Encapsulation:/br>
Package com.evonqa.encapsulation
Class Dog
{
private int size;
private string name;
public void setSize(int 5)
{
size = 5;
}
public void setName(String h)
{
name = h;
}
public int getSize()
{
return size;
}
public string getName()
{
return name;
}
}
public Class Run
{
public static void main(String[] args)
{
Dog d1 = new Dog();
d1.setName("Jimmy");
d1.setSize(8);
System.out.println("Dog size =" + d1.getSize());
System.out.println("Dog name =" + d1.getName());
}
}
Advantages of Encapsulation:
- A class can have 100% control on the data which is stored in the field.
- A class can change the implementation without affecting others program.
- A field can be made read only or write only.
- Users of the class do not know the storage implementation, storage implementation means how data is store.
0 Comment(s)