Java: cannot access a protected member of the superclass in the extending subclass

Classes in other packages that are subclasses of the declaring class can only access their own inherited protected members.

package FirstChapter;

import JustRandomPackage.*;

public class ATypeNameProgram extends YetAnotherClass{
    public ATypeNameProgram() {
        System.out.println(this.variable); // this.variable is visible
    }
}

... but not other objects' inherited protected members.

package FirstChapter;

import JustRandomPackage.*;

public class ATypeNameProgram extends YetAnotherClass{
    public ATypeNameProgram() {
        System.out.println(this.variable); // this.variable is visible
    }

    public boolean equals(ATypeNameProgram other) {
        return this.variable == other.variable; // error: YetAnotherClass.variable is not visible
    }
}

bill is not part of the subclassed YetAnotherClass. bill is a separate YetAnotherClass.

Try int bill = this.variable; (inside a constructor) to access the subclass' members.

Tags:

Java

Protected