Junior — Middle
What are the advantages and disadvantages of using encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
Advantages of encapsulation:
- Hiding internal implementation: the details of an object's operation are hidden from the outside world, allowing internal implementation to be changed without affecting the code that uses the object.
- Data protection: access to object fields is controlled through methods, preventing incorrect modification of the state.
- Simplifying maintenance and extension: changes are localized within the class.
Disadvantages of encapsulation:
- Increased code volume: the need to write getters and setters for field access.
- Potential performance reduction: method calls for access may be slower than direct field access (although in modern languages this is usually negligible).
- Complexity with excessive use: over-encapsulation can lead to many small methods and complicate the code.
Example in Java:
public class User {
private String name; // encapsulated field
public String getName() {
return name;
}
public void setName(String name) {
if(name != null && !name.isEmpty()) {
this.name = name;
}
}
}
Here, the name field is protected from direct access, and through methods, data correctness can be controlled.