Junior — Middle
How can you change the value declared with a private access level?
sobes.tech AI
Answer from AI
In Java, to change the value of a field with private access level, access methods — getters and setters — are usually used. Direct access to a private field from another class is impossible.
Example:
public class MyClass {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
// Usage:
MyClass obj = new MyClass();
obj.setValue(10); // changing private field via setter
int val = obj.getValue(); // getting value via getter
If for some reason getters/setters cannot be used, the value can be changed via reflection, but this is not recommended as it breaks encapsulation and can lead to errors.