Encapsulation is one of the four fundamental OOP concepts. It is a technique used to protect a program's internal characteristics and behavior by creating private fields within a class and providing access to them through public methods. When a field is declared private, it cannot be accessed by anyone outside the class, effectively hiding the fields within the class. Encapsulation thus protects the code and data from unauthorized access by creating a protective wrapper around them.
Encapsulation can be described as a protective barrier that prevents code and data from being randomly accessed by other code defined outside the class. The main benefit of encapsulation is the ability to modify implemented code without breaking the code of others who use it. This feature provides maintainability, flexibility, and extensibility to the code.
For example, consider a data class with two fields: name and remark:
private String name;
private String remark;
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public String getRemark() {
return remark;
}
public void setRemark(int remarkPoints) {
if (remarkPoints >= 5) {
remark = "good";
}
if (remarkPoints < 5) {
remark = "poor";
}
}
}
Another example is a class Phone
with a field weight
. If it is not encapsulated, someone could modify it to have a negative weight. It's better to encapsulate the field using a private variable and provide a setter method where you can add logic for no negative and not over 100 grams.
Think of a real-life example of a car, which is a well-defined composite object with numerous subsystems like transmission, music system, air cooler, or heater system, and others based on the car's price. Each system has its protective layer, so the transmission system does not interfere with the music system or air cooler system. However, there is some integration, such as the transmission charging the battery, which helps to play music. Still, no one can directly modify the behavior of another system. This is how encapsulation hides the complexity of a program.
Benefits of Encapsulation:
- The fields of a class can be made read-only or write-only.
- A class can have total control over what is stored in its fields.
- The main benefit of encapsulation is the ability to modify implemented code without breaking the code of others who use it. Users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.
No comments:
Post a Comment