Junior — Middle
How can data encapsulation be implemented in Java?
sobes.tech AI
Answer from AI
In Java, data encapsulation is achieved through access modifiers and access methods (getters and setters). Class fields are usually declared as private to restrict direct access from external code. Public get and set methods are created to interact with these fields, controlling the reading and modification of values.
Example:
public class User {
private String name; // hidden field
public String getName() { // getter
return name;
}
public void setName(String name) { // setter
if(name != null && !name.isEmpty()) {
this.name = name;
}
}
}
This approach protects the internal state of the object and allows controlling the logic of data modification.