Junior — Middle
What is the purpose of obtaining the value of a property in an object?
sobes.tech AI
Answer from AI
The method of obtaining a property value in an object (getter) is used to control access to the internal fields of a class. It allows:
- Encapsulating data, hiding internal representation.
- Adding logic when reading the value (e.g., validation or computation).
- Ensuring safety and ease of use of the object.
Example in Java:
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Here, the getName() method allows retrieving the value of the name field from outside, without giving direct access to the field itself.