Junior — Middle
How is data hiding and access control to internal class data implemented in Java?
sobes.tech AI
Answer from AI
In Java, hiding internal class data is achieved through encapsulation — restricting access to class fields and methods.
For this, access modifiers are used:
private— access only within the class.protected— access within the package and subclasses.public— access from everywhere.
Usually, class fields are declared as private, and public methods — getters and setters — are created for access:
public class User {
private String name; // hidden field
public String getName() { // getter
return name;
}
public void setName(String name) { // setter
this.name = name;
}
}
This approach allows controlling how data is modified and used, ensuring the security and integrity of the object.