Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have I no access to the protected field?

Tags:

java

I am learning about access levels in java and I have created 3 classes: In package my.inheritance I have class A and class C

package my.inheritance;
public class A {
protected int a=15; 
}

package my.inheritance;
public class C {

public static void main(String[] args)
{
    A a = new A();
    System.out.println(a.a);
}
}

And in another package called my.inheritance.test I have a class B trying to access protected field of int value a but the compiler complains for this!

package my.inheritance.test;
import my.inheritance.A;
public class B extends A{

public static void main(String[] args)
{
    A a = new A();
    int value = a.a;
    System.out.println(value);
}
}

I was under the impression with protected you can access a member from a different class in a different package as long as you subclass it! Why the visibility error then ?

like image 439
Phoenix Avatar asked Aug 06 '12 15:08

Phoenix


2 Answers

Every method can access protected fields of its own class, and all its parent classes. This does not include access to protected fields of another class, even if they have the corresponding base class in common.

So methods in class B can access protected fields from objects of class B, even if they were declared in A, but not from some other object of class A.

One could say that class B inherits the protected members from A, so now every B has those members as well. It doesn't inherit access to the protected members of A itself, so it cannot operate on protected members of any A but only on those of B, even if they were inherited from A.

like image 94
MvG Avatar answered Oct 27 '22 00:10

MvG


Try:

public class B extends A
{

    public static void main(String[] args)
    {
        B a = new B();
        int value = a.a;
        System.out.println(value);
    }
}

You can access a only if it is in the same object.

like image 27
Christian Kuetbach Avatar answered Oct 26 '22 23:10

Christian Kuetbach