簡體   English   中英

如何使用父 class 構造函數(super())為子類創建多個對象?

[英]How do i create multiple objects for child classes using parent class constructor(super())?

class Noodle {

double lengthInCentimeters;
double widthInCentimeters;
String shape;
String ingredients;
String texture = "brittle";

Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
 
 this.lengthInCentimeters = lenInCent;
 this.widthInCentimeters = wthInCent;
 this.shape = shp;
 this.ingredients = ingr;
 
}

public void cook() {
 
 this.texture = "cooked";
 
}

public static void main(String[] args) {
 Pho phoChay = new Pho();
 System.out.println(phoChay.shape);
 
 }
}
class Pho extends Noodle {
Pho(){
 super(30.0,0.64,"flat","rice flour");
}
}

我想再創建一個具有不同參數的 Pho object 我該怎么做? 例如

長度為 20.0 的厘米。

寬度為 0.85 厘米

“膨脹”的形狀

“小麥粉”的成分

只需創建與 super 匹配的所需 args 構造函數:

public class Pho extends Noodle{

    public Pho(double lenInCent, double wthInCent, String shp, String ingr) {
        super(lenInCent, wthInCent, shp, ingr);
    }
}

所以你可以制作你需要的各種面條:

public class Main {

    public static void main(String[] args) {
        Noodle pho = new Pho(30.0,0.64,"flat","rice flour");
        Noodle anotherPho = new Pho(11.0,0.33,"round","bone flour");
    }
}

擴展Noodle class,在子 class 中有一個無參數構造函數,該構造函數使用所需參數調用父super構造函數。

這是一些示例代碼:

class Pho extends Noodle
{
    public Pho()
    {
        super(20.0, .85, "inflated", "wheat flour");
    }
}

暫無
暫無

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

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