Java Tutorial Series - OOPS - Encapsulation
We will learn more about OOPS concepts, We have already covered Inheritance, Polymorphism in recent articles. Let us learn about Encapsulation in this article. Have you ever used predefined function while coding? Do you ever wonder what is the internal logic behind that code? No? This is where encapsulation is implemented, the motive behind using that specific function is achieved without getting into detail. We already understand the access specifiers now which is covered in the recent article, to implement encapsulation, we must be having good understanding of access modifiers in Java. Adding to it, one must use getters and setters as well while implementing encapsulation.
OOPS - Encapsulation -
Encapsulation is a design pattern which gives flexibility to your framework.
Always remember 3 rules if you want to implement Encapsulation -
- Always make instance variable private
- Always make public accessor methods and force calling code to use these methods instead of directly calling the instance variables.
- Use naming convention of get() and set() for these methods.
Let's see an example below to understand more about Encapsulation.
class Plant {
public static final int ID= 7; //remains 7 throughout the program
private String name;
public String getData() {
String data = "some stuff"+ calculateGrowthForecast() ;
return data;
}
private int calculateGrowthForecast() {
return 9;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name=name;
}
}
Benefits of encapsulation
- Code becomes more maintainable and flexible.
- In future we can change our code without breaking our existing code.
- The user of the class don't know how the data is stored.
Comments
Post a Comment