java - 构造函数 Bicycle 类不能应用于给定类型;必需 : int, 找到 int:无参数原因:实际参数和前一个参数长度不同

标签 java inheritance

我有一个从 Bicycle 类扩展的 Tricycle 类,但它显示以下错误

Constructor Bicycle class cannot be applied to given types;required: int,int found:no argument reason:actual and former argument differ in length

public class Bicycle {

/**
 * @param args the command line arguments
 */
    // TODO code application logic here
   int speed;
   int tyre;
   int gear;
   short color;
   // constructor for bicycle class
   public Bicycle(int startSpeed,int startGear){

       speed = startSpeed;
       gear = startGear;

   }
   //set Speed method
   public void setSetStartSpeed(int increaseSpeed){

       speed +=increaseSpeed;
   }

   //set Gear method
   public void setGear(int newGearValue){
       gear = newGearValue;
   }
}


public class Tricycle extends Bicycle {

}

最佳答案

由于 Tricycle 没有定义任何构造函数,因此它隐式地具有一个不带参数的公共(public)构造函数 - 这称为默认构造函数。由于您没有任何代码指定它如何调用其父类(super class)的构造函数,因此默认情况下它只调用 super 的默认构造函数,这当然不存在,因此您会收到您提到的错误。

一种方法是显式定义一个构造函数,将参数传递给 super 构造函数。这似乎是一个合理的解决方案,因为三轮车可以(应该?)也有初始速度和齿轮:

public class Tricycle extends Bicycle {
    public Tricycle(int startSpeed, int startGear) {
        super(startSpeed, startGear);
    }
}

关于java - 构造函数 Bicycle 类不能应用于给定类型;必需 : int, 找到 int:无参数原因:实际参数和前一个参数长度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55342661/

相关文章:

java - 如何使用一定范围内的随机字母值填充二维数组

java - 无法加载 jar - "zip file is empty"

java - 使用 "mappedBy"与 super 类成员的多个 ManyToMany 关系

c++ - 在模板化的嵌套和继承类中未检测到变量

c# - C# 中开放泛型类型继承中的附加类型

c++ - 指向 vector 的变量

java - 如何使用 StringTokenizer 分割路径?

java - 为什么 FindBugs 在显式抛出 NPE 时会发出严重警告?

java - 集群中的 JGroups ReplicatedHashMap

java - 具有来自继承的抽象类的值的构造函数,该抽象类实现了一个接口(interface)