Reputation: 2656
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.
Upvotes: 3
Views: 3374
Reputation: 382150
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 :
Upvotes: 1
Reputation: 328608
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.
Upvotes: 1
Reputation: 15434
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.
Upvotes: 0
Reputation: 18123
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
Upvotes: 0