繁体   English   中英

当其超类具有较少参数时,如何向子类构造函数添加更多参数?

[英]How do I add more arguments to a subclass constructor when its super class has fewer arguments?

我试着寻找这个问题的答案,但我要么是1.没有正确地问到它2.没有正直地思考

基本上,我有一个模拟杂货店的任务。 我有一个Item类,我需要将其用于将从Item类继承特征的子类中。 (遗产)

以下是我到目前为止在本课程中所取得的成就以及其对我的期望

    public class Baguette extends Item {

 int price;
 String name;

public Baguette(String name, int price){
    this.name = name;
    this.price = price;

}

 @Override
 public String getName(){
   return name;

   }
 public int getCost(){
     return price;
     }

}

现在这是法式长棍班级的子类

    public class FlavoredBaguette extends Baguette {
String name;
int price;
String flavor;
int costFlav;

public FlavoredBaguette(String name, int price, String flavor, int costFlav) 
{
    this.name = name; 
    this.price = price; 
    this.flavor = flavor;
    this.costFlav = costFlav;
}
}

这样做后,我在行构造函数Baguette中的Baguette中收到此错误,无法应用于所需的给定类型:字符串,发现int:无参数原因:实际和形式参数列表的长度不同

我知道这与参数数量不同有关,但是我对此一无所知。 谢谢您的帮助!

您需要先调用Baguette的构造函数, super(name, price); ,这意味着FlavoredBaguette不需要nameprice因为它将从Baguette继承这些nameprice

public class FlavoredBaguette extends Baguette {
    //String name;
    //int price;
    String flavor;
    int costFlav;

    public FlavoredBaguette(String name, int price, String flavor, int costFlav) 
    {
        super(name, price);
        //this.name = name; 
        //this.price = price; 
        this.flavor = flavor;
        this.costFlav = costFlav;
    }
}

对于扩展,您无需声明超类的字段。 同样在构造函数中,只需使用参数名称和价格调用super()即可。

public class FlavoredBaguette extends Baguette {
    String flavor;
    int costFlav;

public FlavoredBaguette(String name, int price, String flavor, int costFlav){
    super(name, price);
    this.flavor = flavor;
    this.costFlav = costFlav;
}

编辑:看起来MadProgrammer击败了我:c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM