Why can't I access the data item of the outer class through a reference to the inner class?

class OuterClass1 {

    static private int a = 10;

    void get() {
        System.out.println("Outer Clas Method");
    }

    static class StaticInnerClass {
        void get() {
            System.out.println("Inner Class Method:" + a);
        }
    }

    public static void main(String args[]) {

        OuterClass1.StaticInnerClass b = new OuterClass1.StaticInnerClass();
        b.get();
        System.out.println(b.a);
        System.out.println(b.c);

    }
}

      

I know that a static nested class can access the data members of the outer class, so why can't I access the outer class variable throgh inside the class, but can access it directly using it in the inner class as above?

+3


source to share


2 answers


The Java Language Specification provides the following rules for accessing static fields:

◆ If the field is static:

  • The primary expression is evaluated and the result is discarded. [...]
  • If the field is non-empty final, then the result is the value of the specified class variable in the class or interface that is the type of the primary expression.

Note that the specification does not allow you to search for static fields in other classes; only the immediate type of the primary expression is considered.

In your case, the main expression is simple b

. It is evaluated and its result is discarded with no discernible effect.

The primary expression type b

is OuterClass1.StaticInnerClass

. Therefore Java considers b.a

how OuterClass1.StaticInnerClass.a

. Since the class OuterClass1.StaticInnerClass

does not contain a static field a

, the compiler throws an error.



When you access fields within a class method, a different set of rules apply. When the compiler sees a

in

System.out.println("Inner Class Method:" + a);

      

it looks for the class itself and continues with outer classes when the field is not there. This is where the compiler finds a

, so the expression compiles correctly.

Note. Accessing static members through non-static expressions is a bad idea. See this Q&A question for an explanation .

+3


source


You didn't show us the inner class is StaticInnerClass

not an inner class. There is no such thing as a "static inner class" in Java, because an inner class is by definition a nested class that is not static. Only inner classes have direct access to the members of the contained types. Since StaticInnerClass

it is not an inner class, it has no such access.



0


source







All Articles