Java – static nested subclasses of closed types can still reference private field members. Why?
I've found something vague. With all due respect Suppose 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. } } }
>Why can static nested classes freely access instance members? > Why are protected and private variables accessed differently? However, if the nested class is a non static inner class, is this not the case?
Edit:
>Why does the keyword super allow access to private members of closed types?
Solution
Because B extends A. you do not have access to a's member variable, you are accessing B's inherited member variable
Because the private field is not inherited, and the protected field is; However, private fields still exist in the superclass and are visible through super because B is nested in a The visibility modifier is not expressed enough to express the same content as accessed through super