When inner classes were added to Java in version 1.1 of the language they were originally defined as a transformation to 1.0 compatible code. If you look at an example of this transformation, I think it will make it a lot clearer how an inner class actually works.
Consider the code from Ian Roberts' answer:
public class Foo {
int val;
public Foo(int v) { val = v; }
class Bar {
public void printVal() {
System.out.println(val);
}
}
public Bar createBar() {
return new Bar();
}
}
When transformed to 1.0 compatible code, that inner class Bar
would become something like this:
class Foo$Bar {
private Foo this$0;
Foo$Bar(Foo outerThis) {
this.this$0 = outerThis;
}
public void printVal() {
System.out.println(this$0.val);
}
}
The inner class name is prefixed with the outer class name so as to make it unique. A hidden private this$0
member is added that holds a copy of the outer this
. And a hidden constructor is created to initialise that member.
And if you look at the createBar
method, it would be transformed into something like this:
public Foo$Bar createBar() {
return new Foo$Bar(this);
}
So let's see what happens when you execute the following code.
Foo f = new Foo(5);
Foo.Bar b = f.createBar();
b.printVal();
First we instantiate an instance of Foo
and intialise the val
member to 5 (i.e. f.val = 5
).
Next we call f.createBar()
, which instantiates an instance of Foo$Bar
and initialises the this$0
member to the value of this
passed in from createBar
(i.e. b.this$0 = f
).
Finally we call b.printVal()
which tries to print b.this$0.val
which is f.val
which is 5.
Now that was a regular instantiation of an inner class. Let's look at what happens when instantiating Bar
from outside Foo
.
Foo f = new Foo(5);
Foo.Bar b = f.new Bar();
b.printVal();
Applying our 1.0 transformation again, that second line would become something like this:
Foo$Bar b = new Foo$Bar(f);
This is almost identical to the f.createBar()
call. Again we're instantiating an instance of Foo$Bar
and initialising the this$0
member to f. So again, b.this$0 = f
.
And again when you call b.printVal()
, you are printing b.thi$0.val
which is f.val
which is 5.
The key thing to remember is that the inner class has a hidden member holding a copy of this
from the outer class. When you instantiate an inner class from within the outer class, it it implicitly initialised with the current value of this
. When you instantiate the inner class from outside the outer class, you explicitly specify which instance of the outer class to use, via the prefix on the new
keyword.
new
is an operator in lots of languages. (I thought you may also overloadnew
in C++?) Java's inner class is a bit strange for me, though.