You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用父类构造器(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);
    }
}

实现逻辑说明

  1. 由于父类Noodle仅提供了带参构造器,子类Pho的所有构造器必须显式调用父类构造器(super()),否则编译会报错。
  2. 通过给Pho类新增带参构造器,我们可以将自定义的参数传递给父类构造器,完成子类对象的属性初始化。
  3. 在main方法中,直接通过new Pho(20.0, 0.85, "inflated", "wheat flour")即可创建符合要求的对象。

内容的提问来源于stack exchange,提问作者PRIEST676

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:51:49