Here is the slightly elaborated version of the same question.
We cannot access protected variable (of the superclass) in the subclass,where subclass is in different package.We can access only the inherited variable of the supeclass. But if we change the modifier to ' protected static' then we can access the variable of the superclass too. Why is it like that.?
Here is the code snippet of the same which i was trying to explain.
package firstOne;
public class First {
**protected** int a=7;
}
package secondOne;
import firstOne.*;
public class Second extends First {
protected int a=10; // Here i am overriding the protected instance variable
public static void main (String [] args){
Second SecondObj = new Second();
SecondObj.testit();
}
public void testit(){
System.out.println("value of A in Second class is " + a);
First b = new First();
System.out.println("value in the First class" + b.a ); // Here compiler throws an error.
}
}
The above behavior is expected. But my question is, if we change the access modifier of the superclass instance variable 'a' to 'protected static' then we can access the variable(that of the superclass) too..! What i meant is,
package firstOne;
public class First {
**protected static** int a=7;
}
package secondOne;
import firstOne.*;
public class Second extends First {
protected int a=10;
public static void main (String [] args){
System.out.println("value in the super class" + First.a ); //Here the protected variable of the super class can be accessed..! My question is how and why..?
Second secondObj = new Second();
secondObj.testit();
}
public void testit(){
System.out.println("value of a in Second class is " + a);
}
}
The above code shows the output:
value in the super class 7
value of x in test1 class is 10
How is this possible...?
From "Checking Access to Protected Members in the Java Virtual Machine":
Let m be a member declared in a class c that belongs to a package p. If m is public, it can be accessed by (code in) any class. If m is private, it can be accessed only by c. If m has default access, it can be accessed only by any class that belongs to p.
If m is protected, things are slightly more complicated. First, m can be accessed by any class belonging to p, as if it had default access. In addition, it can be accessed by any subclass s of c that belongs to a package different from p, with the following restriction: if m is not static, then the class o of the object whose member is being accessed must be s or a subclass of s, written o ≤ s (if m is static, the restriction does not apply: m can be always accessed by s).
I found that reference in the JLS, section 6.6.2.1, which supports the part about "the object whose member is being accessed must be s or a subclass...". I don't see anything supporting the static clause, but based on your own example, it's obviously true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With