Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

protected

I want some discussions about this, but I could not infer the answer for my case. Still need help.

Here is my code:

package JustRandomPackage;

public class YetAnotherClass{
    protected int variable = 5;
}
package FirstChapter;

import JustRandomPackage.*;

public class ATypeNameProgram extends YetAnotherClass{
    public static void main(String[] args) {

        YetAnotherClass bill = new YetAnotherClass();
        System.out.println(bill.variable); // error: YetAnotherClass.variable is not visible

    }
}

Some definitions following which, the example above seems to be confusing:

 1. Subclass is a class that extends another class.
 2. Class members declared as protected can be accessed from 
    the classes in the same package as well as classes in other packages 
    that are subclasses of the declaring class.

The question: Why can't I access the protected member (int variable = 5) from a subclass YetAnotherClass instance (bill object)?

like image 342
Mindaugas Bernatavičius Avatar asked Jun 12 '13 05:06

Mindaugas Bernatavičius


1 Answers

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
    }
}
like image 69
Richard JP Le Guen Avatar answered Oct 02 '22 15:10

Richard JP Le Guen