Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not able to access outer class data member through inner class reference?

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 static nested class can access outer class data members so why I am not able to access outer class variable throgh inner class referencebut can access it by directly using it in inner class as above?

like image 666
Ankit Avatar asked Dec 05 '25 09:12

Ankit


1 Answers

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 a non-blank 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 searching for static fields in other classes; only the immediate type of the primary expression is considered.

In your case the primary expression is simply b. It is evaluated, and its result is discarded with no observable effect.

The type of the primary expression b is OuterClass1.StaticInnerClass. Therefore, Java treats b.a as OuterClass1.StaticInnerClass.a. Since OuterClass1.StaticInnerClass class does not contain a static field a, the compiler produces an error.

When you access fields inside a method of the class, a different set of rules is in effect. When the compiler sees a in

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

it searches the class itself, and continues to outer classes when the field is not there. That 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 for an explanation.

like image 160
Sergey Kalinichenko Avatar answered Dec 06 '25 22:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!