protected references in Java

220 views Asked by At

I have three classes:

package pac;

public class A {
    protected A a;  
    protected final int i = 10;
}

public class B extends A {

    void foo() {
        A a = new A();
        int b = a.a.i;  //compiles fine
    }
}

package another.pac;

public class C extends A {

    void foo() {
        A a = new A();
        int b = a.a.i;  //Does not compile. a.a is inaccessible
    }
}

Why can't we access a protected member from a put into another package, but from the same package we can? They both are subclasses of one, therefore acces should have been permitted.

JLS 6.6.2.1 says:

If the access is by a field access expression E.Id, or a method invocation expression E.Id(...), or a method reference expression E :: Id, where E is a Primary expression (ยง15.8), then the access is permitted if and only if the type of E is S or a subclass of S.

The class C satisifies the requerement. What's wrong?

3

There are 3 answers

3
Chetan Kinger On BEST ANSWER

A protected member can be accessed in a subclass outside the package only through inheritance. Try this instead :

public class C extends A {

    void foo() {
       int b = i;  
    }
}
0
mstelz On

Class A is apart of package pac;

and Class C is apart of package another.pac therefore it will be unable to access its member. If C is apart of package pac then it would be able to access the member

See the following post: In Java, difference between default, public, protected, and private

0
Hiren On

There are no needs to make a reference every time. I think you didn't understand Inheritence..

public class B extends A {

    void foo() {
       // A a = new A(); No need to instantiate it here as B extends A
        int b = i;  //No nedd to refer it through a.a.i  
    }
}

package another.pac;

public class C extends A {

    void foo() {
        C c=new C();
        int d=c.i//this will work fine
       //   A a = new A(); same as above explanation
        int b = i;  //same as above and even a.i will not compile
    }
}

Now Your protected variable will be accessible here..