向上转型;为什么我得到输出 11

Upcasting; why do i get the output 11

所以我 运行 这段代码我不明白为什么我得到输出 11:

class Parent{
   protected int counter;
   public Parent(){counter++;}
}

class Child extends Parent{
   public Child(){
     System.out.print(counter);}
  }
}
public class Test{
   public static void main(String [] args){
      Parent p = new Child();
      System.out.print(p.counter);
   }
}
Parent p = new Child();

这将创建 Child class 的实例。这必须执行 Child class 的构造函数。但在此之前它将 运行 Parent class 的构造函数。这会将 counter 的值设置为 1。

接下来,当子 class 构造函数为 运行 时,它会打印 1.

最后一部分很简单。调用 System.out.print(p.counter); 打印另一个 1。因此,结果是 11.

总结:父class的构造函数将在子

之前执行

顺便说一句,这与 upcasting 没有任何关系。是继承。