Accessibility of members of top level class in inner class?

耗尽温柔 提交于 2019-12-12 02:08:45

问题


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?


回答1:


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.
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/6244208/accessibility-of-members-of-top-level-class-in-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!