Junior — Middle
What is the role of private fields in object-oriented programming and why are they used?
sobes.tech AI
Answer from AI
Private fields in object-oriented programming are used to encapsulate data within a class. They hide the internal state of the object from the outside world, allowing access to this data through public methods (getters and setters). This helps protect the object from incorrect usage and ensures data integrity.
For example, if a field stores a user's age, a private field will not allow setting a negative value directly, if the setter is implemented with a check.
public class User {
private int age; // private field
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
}