基本上,我在一本书中做了一个 Java 练习,这个源代码就是该练习的答案。然而,eclipse 说从底部第三行有一个错误,说“- 构造函数 PhoneNumber() 未定义”。但据我了解,该特定构造函数已正确定义,那么问题是什么?
public class PhoneNumber {
// Only the relevant source codes are posted here.
// I removed other bits cause I'm sure they are not responsible for the
// error
private char[] country;
private char[] area;
private char[] subscriber;
public PhoneNumber(final String country, final String area, final String subscriber) {
this.country = new char[country.length()];
country.getChars(0, country.length(), this.country, 0);
this.area = new char[area.length()];
area.getChars(0, area.length(), this.area, 0);
this.subscriber = new char[subscriber.length()];
subscriber.getChars(0, subscriber.length(), this.subscriber, 0);
checkCorrectness();
}
private void runTest() {
// method body
}
public static void main(final String[] args) {
(new PhoneNumber()).runTest(); // error here saying :
// "The constructor PhoneNumber() is undefined"
}
}
最佳答案
Eclipse 是正确的。您的代码未定义不带参数的构造函数,这是您在 main
方法内使用 new PhoneNumber()
调用的构造函数。
你只有一个构造函数,它是:
public PhoneNumber (final String country, final String area, final String subscriber)
如果您不指定任何其他构造函数,系统会自动为您创建所谓的默认构造函数,即不带参数的构造函数。由于您指定了一个具有 3 个参数的参数,因此您没有默认构造函数。
有两种方法可以解决这个问题:
- 声明无参数构造函数;或
- 使用已有的构造函数。
要实现第一个选项,您可以执行如下操作:
class PhoneNumber {
...
public PhoneNumber() {
this("no country", "no area", "no subscriber");
}
}
这将创建一个无参数构造函数,该构造函数只需使用默认参数集调用已有的构造函数。这可能是也可能不是您想要的
要实现第二个选项,请更改您的 main
方法。而不是
(new PhoneNumber ()).runTest();
使用类似的东西:
(new PhoneNumber("the country", "the area", "the subscriber")).runTest();
关于Java 构造函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071149/