Encapsulation is one of the key concepts of Object Oriented programming which has benefits such as flexibility and maintainability. It is defined as hiding the fields of an object without getting updated or misused.
Encapsulation:
Encapsulation is done when the instance variables are marked with the ‘private’ access modifier. Then, having getters and setters (methods) used to set those variables rather than directly using the dot operator.
The getters and setters are also called as properties for each instance variables.
Sample Program:
Male.java
public class Male {
// Not encapsulated
public int weight;
// Encapsulated
private int height;
public int getHeight(){
return height;
}
public void setHeight(int ht){
if(ht > 5 && ht < 8){
height = ht;
} else {
height = 5;
}
}
}
HumanBeing.java
public class HumanBeing {
public static void main(String[] args) {
Male john = new Male();
/**
* Oh no!! we shouldn't let this happen. There should be
* some weight when we create a male. Thats why we need to encapsulate the data.
*/
john.weight = 0;
/**
* Here the height is encapsulated, and even we have placed 2 conditions too.
* If the height is above 5 or below 8 then we accept the given inputs.
* Else we keep 5 as default.
*/
john.setHeight(9);
System.out.println("John's height = " + john.getHeight() +
" John's weight = " + john.weight);
}
}
Output:
John’s height = 5 John’s weight = 0
Even though I am not following encapsulation concept and I am not able to change public instance value of employee class.Please help me to understand the concept where i am going wrong.