Accessing outer class variable via inner class object in main

泄露秘密 提交于 2019-12-05 02:08:51

问题


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

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

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

System.out.println(???);

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.


回答1:


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

The keyword this may be used only in the body of an instance method, instance initializer, or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

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:

It is a compile-time error [ to call C.this] if the current class is not an inner class of class C or C itself.




回答2:


Back in the time, in old versions of Java, you used this$0 as the way to access the outer instance instead of Host.this. The specification has changed but the field is still available through reflection :

Field this$0 = he.getClass().getDeclaredField("this$0");
Host host = (Host) this$0.get(he);
System.out.println(host.x);

I don't know any other way (apart modifying the Host class to add a getX or getHost method).

Now, why isn't this access available without reflection ? I can see two possible reasons :

  • they forgot
  • this access from outside the instance breaks the encapsulation



回答3:


Basic Java concept, Host class can access inner class variable x where as vice versa not possible. You can do like what @Nikita Beloglazov is saying. But directly using variable, not possible




回答4:


You can create method in inner class that returns outer class:

class Helper {
    int x = 7;

    public Host outer() {
        return Host.this;
    }
}

// In main;
System.out.println(he.outer().x);

It is similar to accessing x inside Helper but more general.



来源:https://stackoverflow.com/questions/13700138/accessing-outer-class-variable-via-inner-class-object-in-main

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