通过main中的内部类对象访问外部类变量 [英] Accessing outer class variable via inner class object in main

查看:116
本文介绍了通过main中的内部类对象访问外部类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Host {
    int x=2;

    class Helper {
        int x = 7;
    }

    public static void main(String[] args){
        Host ho = new Host();
        Helper he = ho.new Helper();
        System.out.println(ho.x);
        System.out.println(he.x);

    }
}

所以在这里我得到了预期的输出

So here I'm getting the expected output

2
7

现在我想问一个问题,例如,我想从he访问hox.

Now I wanted to ask that, say, I want to access ho's x from he.

即我想要一些可以通过Helper对象he打印我2的东西:

I.e. I want something here which will print me 2 through the Helper object he:

System.out.println(???);

我知道没有用到这种东西,我只想澄清一下嵌套类的概念. 我认为这应该可行,因为Helper对象he有点绑定"到Host对象ho.如果没有ho,则不可能使用he.从Helper类内部,我可以执行System.out.println(Host.this.x);并且它可以工作.我无法从main内部弄清楚该怎么做.

I know there's no use of such a thing, I just want to clarify my concept of nested classes. I figure that this should be possible, because the Helper object he is sort of 'binded' to the Host object ho. Since he is not possible without ho. From inside the Helper class I can do System.out.println(Host.this.x); and it works. I can't figure out how to do it from inside main.

推荐答案

正如其他答案所指出的,您不能这样做.原因在于this的方式. rel ="nofollow"> JLS#15.8.3

As already pointed out by other answers you can't. The reason lies in the way this is defined in the JLS #15.8.3

关键字this只能在实例方法,实例初始值设定项或构造函数的正文中使用,或在类的实例变量的初始值设定项中使用. 如果它出现在其他任何地方,则会发生编译时错误.

并且由于您只能使用this访问封闭实例(请参见

And since you can only access the enclosing instance with this (cf JLS #15.8.4), that can only be done within the inner class:

如果当前类不是C类或C类本身的内部类,则是编译时错误[调用C.this].

这篇关于通过main中的内部类对象访问外部类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆