PrivateFromOtherInstance

Misconception:

An instance method executing on an object o cannot access private members of some other object p.

Incorrect

An object cannot access private members of other objects of the same class

Correct

An object can access private members of all other objects of the same class

Correction
Here 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).

Symptoms
How do you know your students might have this misconception?

  • Students call a getter method on other objects of the same class.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.