如何修复Java中“Rectangle类构造器无法匹配给定参数”错误?
解决Java构造函数不匹配的编译错误
嘿,我来帮你搞定这个编译错误~ 先看看问题出在哪:
错误原因分析
你遇到的constructor cannot be applied to given types错误,核心问题是你没有正确定义Rectangle类的带参数构造函数:
- 构造函数的名字必须和类名完全一致,你的类叫
Rectangle,但你写的“构造函数”却是MyRectangle,Java会把它当成普通方法,而非构造函数 - 构造函数是没有返回值类型的,你给这些方法加了
double返回值,这就彻底把它们变成普通方法了 - 因为没有自定义构造函数,Java会自动生成一个默认的无参构造函数,所以当你用
new Rectangle(5.0, 10.0, "red")传三个参数时,找不到匹配的构造函数,自然报错
另外还有个小细节:你的color变量加了static修饰,这意味着所有Rectangle对象会共享同一个颜色值,如果你想让每个矩形有自己独立的颜色,得去掉static。
修正后的完整代码
public class MyRectangle { public static void main (String[] args) { Rectangle rectangle1 = new Rectangle(5.0, 10.0, "red"); System.out.println("The width of the first rectangle is " + rectangle1.getWidth() + " the height is " + rectangle1.getHeight() + " the area is " + rectangle1.findArea() + " and the color is " + rectangle1.getColor()); Rectangle rectangle2 = new Rectangle(3.5, 4.3, "yellow"); System.out.println("The width of the second rectangle is " + rectangle2.getWidth() + " the height is " + rectangle2.getHeight() + " the area is " + rectangle2.findArea() + " and the color is " + rectangle2.getColor()); } } class Rectangle { private double width = 1.0; private double height = 1.0; // 去掉static,让每个矩形有自己的颜色 private String color = "white"; // 无参构造函数(显式写出,避免自定义带参构造后无法使用无参实例化) public Rectangle() { } // 带参数的构造函数:名字和类一致,无返回值类型 public Rectangle(double widthParam, double heightParam, String colorParam) { this.width = widthParam; this.height = heightParam; this.color = colorParam; } public double getWidth(){ return width; } public void setWidth(double widthParam){ width = widthParam; } public double getHeight(){ return height; } public void setHeight(double heightParam){ height = heightParam; } public String getColor(){ return color; } // 去掉static,对应成员变量的非静态属性 public void setColor(String colorParam){ color = colorParam; } public double findArea(){ return width * height; } }
关键修改点说明
- 修正构造函数:
- 把原来的
public double MyRectangle()改成public Rectangle()(无参构造) - 把
public double MyRectangle(...)改成public Rectangle(...),去掉返回值类型,并在方法体内给成员变量赋值
- 把原来的
- 调整color变量的static修饰:
- 去掉
color变量的static,同时把setColor方法的static也去掉,让每个矩形对象拥有独立的颜色属性
- 去掉
- 显式写出无参构造:当定义了带参构造函数后,Java不会自动生成无参构造,显式写出它可以保留无参实例化的能力(如果不需要也可以删掉)
这样修改后,你的代码就能正常编译运行,输出两个矩形的各自属性啦~
内容的提问来源于stack exchange,提问作者L.Largent
相关产品推荐
相关产品推荐

