I found something which is ambiguous IMHO. Lets say we have the following class structure:
public class A
{
private int privateVar = 1;
protected int protectedVar = 2;
static class B extends A
{
public int getPrivateVariable()
{
return privateVar; //error: Cannot make a static reference to the non-static field memberVariable
}
public int getProtectedVariable()
{
return protectedVar; //OK: Why?
}
public int getPrivateUnfair()
{
return super.privateVar; //Why this can be accessed using super which the protected member doesn't require.
}
}
}
protected
and private
variables can be accessed? This however, is not the case if the nested class is non-static inner class?super
?
- Why at all does the static nested class has free access to the instance members?
Because B extends A
. You're not accessing the member variables of A
, you're accessing the inherited member variables of B
.
- Why there is a difference in the way protected and private variables can be accessed? This however, is not the case if the nested class is non-static inner class?
Because private fields aren't inherited, whereas protected fields are; but the private fields are still present in the superclass, and visible via super
because B
is nested inside A
. Visibility modifiers aren't sufficiently expressive to articulate the same thing as accessing via super.
Why at all does the static nested class has free access to the instance members?
Nested classes have access to all private members in the same outer class. They are all compiled at once and accessor methods are added to allow this. Note: hte JVM doesn't allow such access which is why accessor methods need to be added.
Why there is a difference in the way protected and private variables can be accessed?
protected members are assumed to be accessed via the super class as they are inherited. Private fields are not inherited, but can be accessed for nested classes.
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