Codecademy学Java遇构造器错误:Droid构造器参数不匹配
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
voidkeyword from the constructor declaration—now Java recognizes it as the official constructor for theDroidclass that takes aStringparameter. - Added an optional
toString()method so when you print therobot1object, you'll see a human-readable message instead of something likeDroid@1234abcd.
Once you make these changes, your code should compile and run without issues!
内容的提问来源于stack exchange,提问作者Gil Y.

