PrivateFromOtherInstance
An instance method executing on an object o
cannot access private members of some other object p
.
An object cannot access private members of other objects of the same class
An object can access private members of all other objects of the same class
CorrectionHere is what's right.
Access permissions are per class, not per object.
Any instance method of a class can access private instance variables of that same class (as long as it has a reference to the object in which those variables are located). So it can access private instance variables of another object!
The following example shows that the compareKeys
method can access the private key
field of this
, but also the private key
field of other
:
public class C {
private int key;
public boolean compareKeys(C other) {
return this.key == other.key;
}
}
More generally: Any (static or instance) method of a class can access private static variables of that same class, and any (static or instance) method of a class can access private instance variables of that same class (as long as it has a reference to the object in which those variables are located).
SymptomsHow do you know your students might have this misconception?
- Students call a getter method on other objects of the same class.