java - 父类中的构造函数不能被应用

标签 java

我正在尝试编写一个程序,该程序采用不同形状的地毯,并使用子类中定义的某些变量创建地毯对象。我的代码是

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();
}

}

但是每当我尝试编译子类时,我都会收到错误

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

我不知道该如何解决它。

最佳答案

由于您的父类(super class)没有无参数默认构造函数,因此您需要使用 super() 从子类构造函数显式调用您的父类(super class)构造函数。 .并不是说这必须是子类构造函数中的第一行。

 public CircleCarpet(String ID, double priceOf, int rad){
    super(ID, priceOf)
    radius = rad;
    super.unitPrice = priceOf;
    computeTotalPrice();

}

建议:

遵循Java命名约定,变量名应采用驼峰命名法。 i.,在这种情况下,idID 更合适。

关于java - 父类中的构造函数不能被应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14649291/

相关文章:

java - 用Java解析.proto文件

java - Android 中的对话列表

java - 在Android中检查用户名和密码

java - 我如何在 Java 中实现一个带有图像和 3 个不同字符串值的数组

java - 如何删除类方法中的 try/catch 重复?

java - JFreeChart 最大缩小

java - 使用 BufferedReader 跳过一行(跳过,但不读取)

java - Android Firebase检查子代中是否存在数据

java - Android:数组循环返回空元素

java - 如何在android中制作一个显示设备硬件规范的应用程序