You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codecademy学Java遇构造器错误:Droid构造器参数不匹配

Fixing Your Droid Constructor Error

Hey there, let's break down what's going wrong here and fix it step by step!

The core issue here is your constructor definition is incorrect. In Java, constructors do NOT have a return type—even void counts as a return type, which turns your "constructor" into a regular method instead.

When you define a method named Droid with void, Java doesn't recognize it as a constructor. Instead, the compiler automatically adds a default no-argument constructor to your class. That's why you're getting the error: it's looking for a constructor that takes no arguments, but you're trying to pass a String.

Here's the corrected code:

public class Droid { 
    int batteryLevel = 100; 
    String name; 

    // Fixed constructor: removed "void"
    public Droid(String droidName){ 
        name = droidName; 
    } 

    // Optional: override toString() to print meaningful info instead of a hash code
    @Override
    public String toString() {
        return "Droid name: " + name + ", Battery level: " + batteryLevel;
    }

    public static void main(String []args){ 
        Droid robot1 = new Droid("Jack"); 
        System.out.println(robot1); 
    }
}

Key changes made:

  • Removed the void keyword from the constructor declaration—now Java recognizes it as the official constructor for the Droid class that takes a String parameter.
  • Added an optional toString() method so when you print the robot1 object, you'll see a human-readable message instead of something like Droid@1234abcd.

Once you make these changes, your code should compile and run without issues!

内容的提问来源于stack exchange,提问作者Gil Y.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:28:28