This is a training exercise for understanding the workings of inner classes in Java. As the question states, how many different versions of x
are accessible in (*)
?
class Outer { int x; class Inner extends Outer { int x; void f(int x) { (*) } } }
I'm inclined to think that there are 3, namely: this.x
, super.x
and x
but some of my peers seem to think that there are 4.
Which of us is confused? And can you explain?
There are 4, namely: x
, this.x
, super.x
and Outer.this.x
.
Consider the following:
public class Outer { int x; public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); outer.x = 3; inner.x = 2; inner.f(1); } class Inner extends Outer { int x; void f(int x) { System.out.println(super.x); System.out.println(x); System.out.println(this.x); System.out.println(Outer.this.x); } } }
This code will print
0 1 2 3
showing 4 different values.
What's happening is the following:
inner
instance has an unitialized x
variable. For an int
, the default value is 0: this is super.x
.f
is called with the argument 1
: this is x
.inner
was set its x
to 2 with inner.x = 2
: this is this.x
.outer
instance, which is Outer.this
was set its x
value to 3: this is Outer.this.x
.The trick here is that Inner
is both an inner class (so it has an enclosing Outer
instance) and a subclass (so it has a parent Outer
instance), and those two Outer
instances are not the same.
There are four of them:
Outer.this.x
for the Outer
class propertythis.x
for the Inner
class property super.x
for the super type Outer
class propertyx
for the method argumentIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With