繁体   English   中英

内部 class 中顶级 class 成员的可访问性?

[英]Accessibility of members of top level class in inner class?

我有一个关于从内部 class 访问顶级 class 的查询。 我刚刚阅读了本地或匿名内部类只能访问最终变量的原因。原因是 JVM 将这两个类作为完全不同的类处理,因此,如果一个 class 中的变量值发生变化,则无法在运行时反映出来时间在另一个 class 文件中。

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? 如果顶级 class 的成员变量的值发生变化,如何在运行时反映在内部 class 的 class 文件中?

它们是单独的类,但在“内部”class 中隐含了对“外部”class 实例的引用。 它基本上充当一个变量,您可以隐式或通过ContainingClassname.this的特殊语法获得它。

请注意,如果您想要这样的隐式引用,则应将嵌套的 class 声明为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.
    }
}

this隐含地是最终的,你不能改变它。 当你写一些像

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

你实际上写的是一样的

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

a不是最终的,但Outer.this是,这是使用的参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM