Java错误:构造函数未定义
在Java中,为什么我会收到此错误:
Error: The constructor WeightIn() is undefined
Java代码:
public class WeightIn{ private double weight; private double height; public WeightIn (double weightIn, double heightIn){ weight = weightIn; height = heightIn; } public void setWeight(double weightIn){ weight = weightIn; } public void setHeight(double heightIn){ height = heightIn; } } public class WeightInApp{ public static void main (String [] args){ WeightIn weight1 = new WeightIn(); //Error happens here. weight1.setWeight(3.65); weight2.setHeight(1.7); } }
我有一个构造函数定义。
将此添加到您的class级:
public WeightIn(){ }
- 请理解,只有在没有编写其他构造函数时才提供默认的无参数构造函数
- 如果你编写任何构造函数,那么编译器不提供默认的no-arg构造函数。 你必须指定一个。
在这你不能做WeightIn weight1 = new WeightIn();
因为没有定义默认构造函数。
所以你可以添加
public WeightIn(){ }
或者你可以这样做
WeightIn weight1 = new WeightIn(3.65,1.7) // constructor accept two double values
你没有构造函数WeightIn()。创建它或将main方法中的参数赋给构造函数。
WeightIn weight1 = new WeightIn();
未定义默认构造函数。 请像这样定义: –
public weightIn() { }
编译器在此行上遇到对“ WeightIn()
”无参数构造函数的调用:
WeightIn weight1 = new WeightIn(); //Error happens here.
编译器在类定义中寻找匹配的构造函数,而不是找到它。 那是错误。 (你确实有一个构造函数定义:“ WeightIn(double,double)
”但是它有两个参数,并且不匹配。)
解决这个问题的几种方法。
最简单的方法是更改main方法中的代码以传递两个参数。
WeightIn weight1 = new WeightIn( 3.65, 1.7); //weight1.setWeight(3.65); //weight2.setHeight(1.7);
对setWeight
和setHeight
方法的调用是多余的,因为构造函数方法已经为成员分配了值。
首先,您应该知道一个.java文件只能有一个公共类。
您收到错误是因为您已编写参数化构造函数并访问默认构造函数。 要修复此错误,请写入:
WeightIn weight1 = new WeightIn(5.2, 52.2);
代替
WeightIn weight1 = new WeightIn();