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

发布于 2024-11-14 08:32:49 字数 217 浏览 2 评论 0原文

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

然后,我的问题是,内部成员类(非静态)如何访问顶级类的成员,因为 JVM 仍然将这两个类视为不同的类文件?如果顶级类的成员变量的值发生变化,运行时如何反映到内部类的类文件中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅黛梨妆こ 2024-11-21 08:32:49

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

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

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.
    }
}
旧伤慢歌 2024-11-21 08:32:49

this 是隐式最终的,您无法更改它。当你写一些像

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

你实际上写的东西一样的

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

东西时,a不是最终的,但Outer.this是,这就是所使用的引用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文