public class Outer2 {
Outer2(){
System.out.println("Calling Outer2 constructor");
System.out.println(this.getClass().getName() + ": Inner class reference is " + this);
System.out.println(Outer2.this + ": Outer class reference is " + Outer2.this);
}
class Inner1 extends Outer2 {
Inner1() {
System.out.println("Calling Inner1 constructor");
System.out.println(this.getClass().getName() + ": Inner class reference is " + this);
System.out.println(Outer2.this + ": Outer class reference is " + Outer2.this);
}
}
class Inner2 extends Inner1 {
Inner2() {
System.out.println("Calling Inner2 constructor");
System.out.println(this.getClass().getName() + ": Inner class reference is " + this);
System.out.println(Outer2.this + ": Outer class reference is " + Outer2.this);
}
}
public static void main(String[] args) {
new Outer2().new Inner2();
}
}
Can someone explain why the above code gives the following output:
有人可以解释为什么上面的代码给出了以下输出:
Calling Outer2 constructor
outer2.Outer2: Inner class reference is outer2.Outer2@15db9742
outer2.Outer2@15db9742: Outer class reference is outer2.Outer2@15db9742
Calling Outer2 constructor
outer2.Outer2$Inner2: Inner class reference is
outer2.Outer2$Inner2@6d06d69c
outer2.Outer2$Inner2@6d06d69c: Outer class reference is
outer2.Outer2$Inner2@6d06d69c
Calling Inner1 constructor
outer2.Outer2$Inner2: Inner class reference is
outer2.Outer2$Inner2@6d06d69c
outer2.Outer2@15db9742: Outer class reference is outer2.Outer2@15db9742
Calling Inner2 constructor
outer2.Outer2$Inner2: Inner class reference is
outer2.Outer2$Inner2@6d06d69c
outer2.Outer2@15db9742: Outer class reference is outer2.Outer2@15db9742
I'm interested in why the inner and outer class reference equals when calling Outer2 supertype constructor second time?
我很感兴趣为什么内部和外部类引用在第二次调用Outer2超类型构造函数时相等?
1 个解决方案
#1
1
In the Outer2 constructor, you're not in any inner class of Outer2. So, for the compiler, the line
在Outer2构造函数中,您不在Outer2的任何内部类中。所以,对于编译器来说,这一行
System.out.println(Outer2.this + ": Outer class reference is " + Outer2.this);
is strictly equivalent to
严格等同于
System.out.println(Outer2.this + ": Outer class reference is " + this);
So the value of this
, is printed twice. And since this
is actually a reference to the Inner2 object being created, it prints outer2.Outer2$Inner2@6d06d69c
.
所以它的价值打印两次。由于这实际上是对正在创建的Inner2对象的引用,因此它打印outer2.Outer2$Inner2@6d06d69c。
#1
1
In the Outer2 constructor, you're not in any inner class of Outer2. So, for the compiler, the line
在Outer2构造函数中,您不在Outer2的任何内部类中。所以,对于编译器来说,这一行
System.out.println(Outer2.this + ": Outer class reference is " + Outer2.this);
is strictly equivalent to
严格等同于
System.out.println(Outer2.this + ": Outer class reference is " + this);
So the value of this
, is printed twice. And since this
is actually a reference to the Inner2 object being created, it prints outer2.Outer2$Inner2@6d06d69c
.
所以它的价值打印两次。由于这实际上是对正在创建的Inner2对象的引用,因此它打印outer2.Outer2$Inner2@6d06d69c。