Junior — Middle
How is the principle of data hiding implemented in Java to ensure encapsulation?
sobes.tech AI
Answer from AI
In Java, the principle of data hiding is implemented using access modifiers and encapsulation of class fields. The main steps:
- Declare class fields as private so they are not directly accessible from other classes.
- Provide public access methods (getters and setters) to manage reading and modifying these fields.
Example:
public class User {
private String name; // hidden field
public String getName() { // public getter
return name;
}
public void setName(String name) { // public setter
this.name = name;
}
}
Thus, the internal state of the object is protected from direct access, allowing control over data modification logic and maintaining invariants.