无法应用父类中的构造函数 [英] Constructor in parent class cannot be applied
问题描述
我正在尝试编写一个采用不同形状地毯的程序,并使用子类中定义的某些变量创建一个地毯对象。我的代码是
I'm trying to code a program that takes different shapes of carpets and creates a carpet object with certain variables defined in the subclasses. My code is
public abstract class Carpet{
protected int area = 0;
protected double unitPrice = 0;
protected double totalPrice = 0.0;
protected String carpetID;
public Carpet(String id, double thisPrice){
carpetID = id;
unitPrice = thisPrice;
}
public String getCarpetId(){
return carpetID;
}
public String toString(){
String carpet = new String("\n" + "The CarpetId:\t\t" + getCarpetId() + "\nThe Area:\t\t" + area + "\nThe Unit Price\t\t" + unitPrice + "\nThe Total Price\t" + totalPrice + "\n\n");
return carpet;
}
public abstract void computeTotalPrice();
}
且子类是
public class CircleCarpet extends Carpet{
private int radius;
public CircleCarpet(String id, double priceOf, int rad){
radius = rad;
super.unitPrice = priceOf;
computeTotalPrice();
}
public void computeTotalPrice(){
super.area = radius * radius * 3;
super.totalPrice = area * unitPrice;
}
public String toString(){
String forThis = new String("\nThe Carpet Shape:\tCircle\nThe radius:\t\t" + radius + "\n");
return forThis + super.toString();
}
}
但每当我尝试编译子类我得到错误
But whenever I try to compile the subclass I get the error
11: error: constructor Carpet in class Carpet cannot be applied to given types;
public CircleCarpet(String ID, double priceOf, int rad){
^
required: String,double
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Tool completed with exit code 1
我不知道如何解决这个问题。
I'm not sure what to do to fix it.
推荐答案
作为你的超级class没有 no-args默认构造函数,
你需要使用 super() 。这不一定是你的第一行子类构造函数。
As your super class doesn't have a no-args default constructor,
you need to explicitly call your super class constructor from your sub-class constructor using super().Not that this has to be the first line in your sub-class constructor.
public CircleCarpet(String ID, double priceOf, int rad){
super(ID, priceOf)
radius = rad;
super.unitPrice = priceOf;
computeTotalPrice();
}
建议:
遵循Java命名约定,变量名应为camelCase。 i。,在这种情况下, id
比 ID
更合适。
Follow Java naming conventions, variable names should be camelCase. i., in this case id
is more appropriate than ID
.
这篇关于无法应用父类中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!