abksrv abksrv - 20 days ago 6
Java Question

Static nested sub-classes of the enclosing type can still refer to the private field members, why?

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.
}
}
}



  1. Why at all does the static nested class has free access to the instance members?

  2. 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?



EDIT:




  1. Why is the private member of the enclosing type allowed to be accessed by the keyword
    super
    ?


Answer
  1. 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.

  1. 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.