显式强制转换调用构造函数?

jub*_*kon 1 java oop static casting

我有两节课AB

问题:为什么该行System.out.println(b.x)结果打印 23?

我同意结果为 22,因为 的构造函数A和 每个构造函数都会将 1B递增static int y

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
}    
Run Code Online (Sandbox Code Playgroud)

Lor*_*uro 5

b.y23因为B构造函数也调用A构造函数,使用super(x + 0.f);.

因此y增加 3 倍,1 倍 inA a = new A(10f);和 2 倍 inB b = new B();