Sobes.tech
Junior — Middle

Kas on võimalik muuta klassis deklareeritud privaatset väärtust?

sobes.tech AI

Vastus AI-lt

In Java, a value declared as private (private) cannot be directly modified from code outside the class in which it is declared. However, within the same class, a private field can be freely modified. To access and modify private fields from other classes, access methods (getters and setters) are usually used. For example:

public class Person {
    private String name; // private field

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name; // modification of private field via setter
    }
}

Thus, privacy restricts access to the field from outside, but does not prohibit its modification inside the class.