Protected links in Java

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 the protected member from a package to another package, but from the same package we can? They are both subclasses of one, so acces should be allowed.

JLS 6.6.2.1 says:

If access is by an access expression to the field E.Id or a method call expression E.Id (...) or a method reference expression E :: Id, where E is the primary expression (ยง15.8), then access is allowed if and only if when type E is S or a subclass of S.

The class C

satisfies the requirement. What's wrong?

+3


source to share


3 answers


A protected

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



public class C extends A {

    void foo() {
       int b = i;  
    }
}

      

+4


source


There is no need to make a link every time. I think you misunderstood Inheritance ..

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
    }
}

      



Your protected variable will now be available here.

+2


source


Class A is different from the pac package;

and class C is different from another.pac package so it won't be able to access its member. If C is different from the pac package then it will be able to access the item

See the following post: In Java, the difference between standard, public, secure and private

+1


source







All Articles