Junior — Middle
Explain the mechanism of how the method for setting an object's property value works.
sobes.tech AI
Answer from AI
In Java, a method that sets the value of an object's property is usually called a setter. It is a method that allows setting the value of a private class field from outside, ensuring encapsulation.
The mechanism of a setter works as follows:
- A private field is declared in the class, for example
private String name;. - A public method named
setNameis created, which takes a parameter of the required type. - Inside the method, the value of the parameter is assigned to the private field.
Example:
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
Thus, the setter controls the modification of the object's state, allowing for checks or logic to be added when setting the value, such as null checks or validation.