gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:40 25 4
gpt4 key购买 nike

我有一个从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com