Junior — Middle
Is it possible to modify a value declared as private in a class?
sobes.tech AI
Answer from AI
In Java, a value declared as private cannot be directly modified from code outside the class in which it is declared. However, within the class itself, a private field can be freely changed. 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 within the class.