Why have I no access to the protected field?

Viewed 4848

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 ?

5 Answers
Related