Sobes.tech
Junior — Middle

How should values be set for class attributes?

sobes.tech AI

Answer from AI

Values for class attributes in Java are usually set through constructors, setters (set methods), or directly if the attributes have an access modifier that allows it.

Most often, encapsulation is used: attributes are declared as private, and public setXxx() methods are created for setting values. This allows controlling the correctness of data.

Example:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        }
    }
}
How should values be set for class attributes? — Java - sobes.tech