如何使用父类构造器(super())创建子类的多个不同参数对象?
如何使用父类构造器(super())创建子类的多个对象
要创建符合指定参数要求的Pho对象,只需给Pho类重载构造器,通过带参构造器调用父类Noodle的构造器传入目标参数即可。具体实现如下:
修改后的完整代码
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对象 Pho phoChay = new Pho(); System.out.println(phoChay.shape); // 输出: flat // 创建指定参数的新Pho对象 Pho customPho = new Pho(20.0, 0.85, "inflated", "wheat flour"); System.out.println(customPho.shape); // 输出: inflated System.out.println(customPho.ingredients); // 输出: wheat flour } } class Pho extends Noodle { // 原有无参构造器,创建默认参数的对象 Pho() { super(30.0, 0.64, "flat", "rice flour"); } // 新增带参构造器,支持自定义参数初始化 Pho(double len, double width, String shape, String ingredients) { super(len, width, shape, ingredients); } }
实现逻辑说明
- 由于父类
Noodle仅提供了带参构造器,子类Pho的所有构造器必须显式调用父类构造器(super()),否则编译会报错。 - 通过给
Pho类新增带参构造器,我们可以将自定义的参数传递给父类构造器,完成子类对象的属性初始化。 - 在
main方法中,直接通过new Pho(20.0, 0.85, "inflated", "wheat flour")即可创建符合要求的对象。
内容的提问来源于stack exchange,提问作者PRIEST676
相关产品推荐
相关产品推荐

