java - 错误: constructor Droid in class Droid cannot be applied to given types;

标签 java constructor program-entry-point default-constructor

我正在 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/

相关文章:

java - 无效文件(错误的魔数(Magic Number)):how I could solve this when I execute JAR file not works using this java code?

java - TestNG @BeforeClass 初始化代码在 Test 之前未运行

java - 在 Java 中使用 Student 类中的 Address 类和 toString

java - 设计实现代码: static or dynamic?

Java - 非常长的 switch case 的替代方案

java - 基于日期按小时/半小时的 Bin Java 时间戳

java - 缺少生产目录; Intellij运行程序时找不到主类文件

c - 同一项目下不同源文件中的两个main()

c++ - 模板类的专用构造函数

Java 复制构造函数 ArrayLists