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

标签 java oop casting static

我有两个类 AB

问题:为什么 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.y23 因为 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/

相关文章:

java - 使用编码代码对字符串进行编码

java - 每次有 2 个元素的 for 循环中数组索引超出范围

C++ 安全高效地将 std::weak_ordering 转换为 int

java - 使用自定义类路径使用 GraalVM native 镜像命令行?

Java Swing ; JScrolledPane 中嵌入的 JTable 的水平滚动问题

java - 如何在 OOP 中实现图形层次结构

c++ - 在列表中调用子对象

c++ - 从函数返回局部值而不触发复制构造函数

c# - C# 中对象类型转换 (as/(int)) 的区别

c++ - 这段代码中关于 n 在 pc[i] 中的表示是怎么回事