Junior
Fields address and phone are public. Why are public fields disliked in Java? What really changes when switching to private + getter/setter?
sobes.tech AI
Answer from AI
In Java, public fields are not recommended because they violate the principle of encapsulation — one of the fundamentals of object-oriented programming. When using public fields:
- There is no control over how and when data is changed.
- It is impossible to add logic when reading or writing (e.g., validation).
- It is difficult to change the internal implementation of a class without affecting external code.
Switching to private fields with getter/setter allows:
- Controlling access to fields (e.g., making a field read-only).
- Adding additional logic when getting or setting a value (validation, transformation).
- Maintaining compatibility when changing the internal structure of the class.
Example:
public class User {
private String phone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
if (phone != null && phone.matches("\\+\\d{11}")) {
this.phone = phone;
} else {
throw new IllegalArgumentException("Invalid phone number");
}
}
}
This approach makes the code more reliable and maintainable.