Skip to content
Advertisement

How static nested class has this pointer

Today I was reading about static nested class and I am little confused because of below code.

class testOuter {
    int x;
     static class inner {
       int innerVar; 
    public void testFunct() {
        x = 0;       // Error : cannot make static reference to non static field
        innerVar = 10;
        outerFunc(this);
     }
     }
     static void outerFunc(SINGLETON s) {
         
     }
}

What I understood about static nested class is, it behaves like a static member of outer class. It can refer only static variables and can call static methods. From the above code, the error at x=0 is fine.

But what I am confused is if its behaves like static block, then it is allowing me to modify innerVar, which is not static and also how can it have this pointer. So if the nested class is static then the method inside or not static implicitly?

Advertisement

Answer

Write static int x instead of int x, then it will work. As you said yourself, static inner class can access only static members of outer class. Since x is not static in your code, you can’t access it.

P.S.

Note, that ALL normal classes are static, i.e. one instance of class information exists per application run. So, when you declare inner class being static, you just state that it is just as normal class.

Contrary, non-static inner classes are different. Each instance of non-static inner class is a closure, i.e. it is tied to some INSTANCE of outer class. I.e. you can’t create instance of non-static inner class without respect of some outer class instance.

P.P.S.

Ah sorry, you didn’t highlight this and innerVar. Both are non-static members of inner class, so you can access them. You cannot access non-static members only if they belong to OUTER class.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement