Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 867
abksrv Avatar asked Feb 05 '23 16:02

abksrv


2 Answers

  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.

like image 64
Andy Turner Avatar answered Feb 16 '23 02:02

Andy Turner


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.

like image 27
Peter Lawrey Avatar answered Feb 16 '23 02:02

Peter Lawrey