0

I have a query regarding accessibility of top level class from member inner class. I have just read the reason why local or anonymous inner classes can access only final variables.The reason being JVM handles these two classes as entirely different classes and so, if value of variable in one class changes, it can't be reflected at run time in another class file.

Then, my question is that how an inner member class (non-static) can have access to members to members of top level class, as JVM is still treating these two classes as different class files? If value of a member variable of top level class changes, how will it possible to reflect in class file of inner class at runtime?

mtsz
  • 2,725
  • 7
  • 28
  • 41
Sumit Desai
  • 1,542
  • 9
  • 22

2 Answers2

5

They're separate classes, but there's an implicit reference to the instance of the "outer" class in the "inner" class. It basically acts as a variable which you can get at either implicitly or via special syntax of ContainingClassname.this.

Note that if you don't want such an implicit reference, you should declare the nested class as static:

public class Outer
{
    private class Inner
    {
        // There's an implicit reference to an instance of Outer in here.
        // For example:
        // Outer outer = Outer.this;
    }

    private static class Nested
    {
        // There's no implicit reference to an instance of Outer here.
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • but then, in case of local classes(method level), why can't they also have such implicit reference of top level classes to directly use it's members instead of declaring them final? – Sumit Desai Jun 05 '11 at 17:19
  • @Sumit: Because the inner class doesn't have a copy of the variables themselves - just a reference to the instance of the outer class. It's only *local* variables which end up having copies made in anonymous inner classes. You can access *instance* variables from the enclosing instance without them being final, even in anonymous inner classes. – Jon Skeet Jun 05 '11 at 17:21
  • actually, i was little confused between local n instance variables in this case...now i got it.... @Jon..Thanks a lot.. – Sumit Desai Jun 05 '11 at 17:39
1

this is implicitly final, you cannot change it. When you write some thing like

class Outer {
    int a;
    class Inner {
       { a = 1; }
    }
}

you are actually writing the same as

class Outer {
    int a;
    class Inner {
       { Outer.this.a = 1; }
    }
}

The a is not final but the Outer.this is, and that is the reference which is used.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130