Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing outer class variable via inner class object in 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

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.

like image 940
user1265125 Avatar asked Dec 09 '25 06:12

user1265125


2 Answers

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.

like image 147
assylias Avatar answered Dec 10 '25 18:12

assylias


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
like image 20
Denys Séguret Avatar answered Dec 10 '25 19:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!