![](/img/trans.png)
[英]How to initialize parameter Objects in child class needed for super class constructor?
[英]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.