我正在 Codecademy 上学习 java,在一个非常简单的文件中,我收到此错误消息,该消息与构造函数参数有关。
我搜索了其他类似的问题/答案,但它们是关于缺少参数的,我认为这里不是这种情况。
public class Droid {
//parameters
int batteryLevel=100;
String name;
//constructor
public void Droid(String droidName){
name=droidName; }
//main
public static void main(String []args){
Droid robot1 = new Droid("Jack");
System.out.println(robot1);
}
错误:类 Droid 中的构造函数 Droid 无法应用于给定类型; Droid 机器人1 = new Droid("Jack"); ^ 必需:无参数 发现:字符串 原因:实际参数列表和正式参数列表的长度不同 1 个错误
最佳答案
从构造函数中删除返回类型:
public Droid(String droidName){
name=droidName; }
参见Why do constructors not return values
the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime.
关于java - 错误: constructor Droid in class Droid cannot be applied to given types;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56206526/