Java构造函数未定义

时间:2013-04-17 22:12:18

标签: 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"
    }
}

3 个答案:

答案 0 :(得分:6)

Eclipse是正确的。您的代码没有定义没有参数的构造函数,这是您在new PhoneNumber()方法中使用main调用的内容。

您只有一个构造函数,即:

public PhoneNumber (final String country, final String area, final String subscriber)

如果您未指定任何其他构造函数,则会自动为您创建所谓的默认构造函数,即没有参数的构造函数。由于您指定了一个包含3个参数的参数,因此您没有默认构造函数。

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

  1. 声明no-arg构造函数;或
  2. 使用您已有的构造函数。
  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();
    

答案 1 :(得分:1)

如果您没有定义任何其他构造函数,则仅为您自动定义默认(无参数)构造函数。

答案 2 :(得分:0)

你的错误说的是没有

PhoneNumber()

构造函数已定义(没有参数)。默认情况下,如果您没有声明任何其他构造函数,那么这是您在Java中可用的构造函数。但是你通过实施

来覆盖它
PhoneNumber (final String country, final String area, final String subscriber)