Java 构造函数未定义

标签 java

基本上,我在一本书中做了一个 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 个参数的参数,因此您没有默认构造函数。

有两种方法可以解决这个问题:

  1. 声明无参数构造函数;或
  2. 使用已有的构造函数。

要实现第一个选项,您可以执行如下操作:

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/

相关文章:

java - 在 java 中维护唯一数组的 ArrayList

Java反斜杠字符未在字符串中输出

java - "Application not responding"并且用户选择 "close"应用程序而不是 "wait"

java - 从 Windows 中的 Eclipse 中运行 MapReduce 作业时出错

java - Servlet 过滤器 URL 模式 - 如何匹配特定 servlet 也调度请求的所有 servlet

java - 如何使用 Junit 和 Java 模拟和编写 Azure 服务总线主题的单元测试?

java - 如何从另一个 Rest 服务调用 HTTPS Rest 服务?

java - 使用git bash时无法识别java命令

java - 在方法中返回文档

java - 无法在弹出的新窗口中访问框架内的网络元素