Search code examples
javaprotected

java protected why is this working through non-inheritance?


I'm obviously missing the obvious in this but given:

package a;
public class Class1 {
    protected int a=1;
}

package b;
import a.*;

public class Class2 extends Class1 {
    Class2() {
        Class1 c1=new Class1();
        Class2 c2=new Class2();
        System.out.println(a);     //1
        System.out.println(c1.a);  //2
        System.out.println(c2.a);  //3
    }
}

I know //1 is fine due to being used through inheritance and //2 fails because it's not being access through inheritance, but why is //3 ok too? I thought variable a was being accessed through a new object and a resides in Class1?

Thanks.


Solution

  • When you are manipulating an object inside its class, you have full access to all his attributes, including the private ones. As c2 is a instance of Class2 and you are manipulating it inside the Class2 code, you can see the protected attribute.