簡體   English   中英

關於超類和子類的構造函數的問題

[英]Question about constructor of superclass and subclass

為什么代碼 (1) 不會導致錯誤,而代碼 (2) (3) 會?

我認為當子類調用構造函數時,它會首先調用超級 class 構造函數,但我不知道為什么代碼(1)是對的而其他兩個是錯誤的。

//(1)

public class Parent {
  public int a;

  public Parent() {
    this.a = 0;
  }
}

public class Child extends Parent {
  public Child() {}
}

//(2)

public class Parent {
  public int a;

  public Parent(int number) {
    this.a = number;
  }
}

public class Child extends Parent {
  public Child() {}
}

//(3)

public class Parent {
  public int a;

  public Parent(int number) {
    this.a = number;
  }
}

public class Child extends Parent {
  public Child(int numb) {      
  }
}

代碼(1)是正確的,而其他兩個是錯誤的。

注意:如果構造函數沒有顯式調用超類構造函數,Java 編譯器會自動插入對超類的無參數構造函數的調用。 如果超級 class 沒有無參數構造函數,則會出現編譯時錯誤。 Object 確實有這樣的構造函數,所以如果 Object 是唯一的超類,是沒有問題的。

因此,在這里,您的代碼 (2)(3) 沒有無參數構造函數,而且您沒有顯式調用具有參數的構造函數,因此出現編譯時錯誤。 更多細節來自https://docs.oracle.com/javase/tutorial/java/IandI/super.html

在代碼 1 中, Parent的構造函數沒有 arguments,因此對默認構造函數的調用是隱式的:

public Child () {
    super();
} /* This code is not necessary, but is implied. */

但是在代碼 2 和 3 中,構造函數有一個參數,並且由於沒有提供無參數的重載,因此必須提供對超類構造函數的調用。 為此,您必須引用super()

public class Parent {
    public int a;

    public Parent(int number) {
        this.a = number;
    }
}

public class Child extends Parent {
    public Child(int numb) {
        super(numb); // Calls Parent(int) and sets this instance’s Parent.a value to numb.
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM