Sobes.tech
Junior — Middle

What is the purpose of the method for setting a value in an object?

sobes.tech AI

Answer from AI

The setter method in an object is intended to modify the value of a private or protected class field. It provides access control to the internal data of the object, allowing the value to be set with checks or additional logic. This is part of encapsulation — an OOP principle that protects the internal state of an object from direct external modification.

Example in Java:

public class Person {
    private String name;

    // Setter
    public void setName(String name) {
        if(name != null && !name.isEmpty()) {
            this.name = name;
        }
    }

    // Getter
    public String getName() {
        return name;
    }
}
What is the purpose of the method for setting a value… - sobes.tech