我有两个类 A
和 B
。
问题:为什么 System.out.println(b.x)
行的结果是 23?
我同意 22 作为结果,因为 A
的构造函数和 B
的构造函数各自将 static int y
递增 1 .
public class A {
public long x = 0;
public static int y = 20;
public A(float x) {
this((int) x );
A.y++;
}
public A(int x) {
this.x = x;
}
public int f(double d) {
return 1;
}
public int f(long l) {
return 2;
}
}
public class B extends A {
public int x = 1;
public B() {
this(42);
B.y++;
}
public B(int x) {
super(x + 0.f);
this.x += this.x;
}
public int f(long l) {
return 3;
}
public int f(float f) {
return 4;
}
}
public class M {
public static void main(String[] args) {
A a = new A(10f);
System.out.println(a.x);
System.out.println(A.y);
B b = new B();
System.out.println(((A b).x); // 23
}
最佳答案
b.y
是 23
因为 B
构造函数也调用了 A
构造函数,使用 super( x + 0.f);
.
因此 y
递增 3 次,1 次在 A a = new A(10f);
中,2 次在 B b = new B() ;
关于java - 显式强制转换调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522121/