Encapsulation



Encapsulation


Encapsulation is One of the most important feature of object oriented programming.
Encapsulation provides maintainability and flexibility.

If Your java class is used by many developers then they have a chance to change
your class properties.That causes other developers code which is used your class properties will be in trouble.
Encapsulation comes into picture to handle this kind of scenario.

We have to follow some rules to provide encapsulation to our class

Keep instance variables protected (with an access modifier, often private).

■ Make public accessory methods, and force calling code to use those methods
rather than directly accessing the instance variable.

■ For the methods, use the Java Beans naming convention of
set and get.


Example : We developed a Java class Company

class Company{

private int companyId;

private String Name;

private String address;


//provide public getter and setter methods for all properties

public void setCompanyId(int companyId){
this.companyId=companyId;
}

public void setName(String name){
this.name=name;
}


public void setAddress(String address){
this.address=address;
}


public int getCompanyId(){

return companyId;
}

public int getName(){

return name;
}

public int getAddress(){

return address;
}


}


The above code is very useful.Even though you added any code to your java class.
That never effects your api.In this way encapsulation provides security and maintainability
to our java class.

Comments