簡體   English   中英

在Java中從父級調用子類構造函數

[英]Call subclass constructor from parent in Java

所以我正在學習java繼承,我遇到了一個我不知道如何解決的情況。

我想要做的是從超類中調用子類構造函數。 我不知道這是否有意義,但我會嘗試用一個例子來解釋自己。

public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}

public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}

我為什么要那樣做?

我希望能夠不必主要處理SmartPhone。
我希望能夠做到:

Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

這毫無意義。 如果您需要SmartPhone實例,則必須致電

Phone iphone = new SmartPhone("iPhone", 368, "4G");

不能從超類構造函數中調用子類構造函數。

如果您希望通過傳遞的參數確定Phone的類型,則可以使用靜態工廠方法:

public class PhoneFactory {

    public static Phone newPhone (String brand, int weight) {
        return new Phone(brand, weight);
    }

    public static Phone newPhone (String brand, int weight, String tech) {
        return new SmartPhone(brand, weight, tech);
    }
}

Phone nokia = PhoneFactory.newPhone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = PhoneFactory.newPhone("iPhone", 368, "4G"); // <- SmartPhone instance

不可能在基類的構造函數中調用子類的構造函數。 這有多種原因,但其中一個原因是派生類的構造函數,隱含地或顯式地調用基類的構造函數。 這會導致無限循環。
您可以做的是:在基類中創建一個靜態方法,決定應該創建哪個實例。

public class Phone
{
  ...

  public static Phone createPhone(String brand, int weight, String tech)
  {
    if (tech == null)
      return (new Phone(brand, weight));
    else
      return (new SmartPhone(brand, weight, tech));
  }

  ...

}

您可以使用私有構造函數,並使用三個參數從Phone()構造函數中實例化一個SmartPhone()對象。

暫無
暫無

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

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