WHY use encapsulation

Encapsulation is basically data hiding. If you don't want your variables and methods to be exposed to outside world, you use encapsulation by using the access specifier for the variables and function.


public class WeightPerson
{
private int weight;
private int size;
}

now, to enforce encapsulation, you provide accessor methods to force calling code to use them instead of directly access the instance variable.

Maintainability and flexibility is the key here. Without encapsulation, we can have a calling code
public class BadOoExample
{
public static void main(String[]args){
PersonWeight wt= new PersonWeight();
wt.size=-5;}
}
Size is set negative here which is legal but not desirable.
Using accessor methods can avoid such problems.