2013-04-17 48 views
2

基本上,我在一本書中做了一個Java練習,這個源代碼就是它對練習的回答。然而,eclipse說在底部的第三行有一個錯誤,說「構造函數PhoneNumber()是未定義的」。但據我瞭解,這個特定的構造函數是正確定義的,所以問題是什麼?Java構造函數undefined

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" 
    } 
} 

回答

6

Eclipse是正確的。你的代碼沒有定義一個沒有參數的構造函數,這是main方法中用new PhoneNumber()調用的函數。

你只有一個構造函數,它是:

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

所謂默認構造函數,在一個不帶參數,爲你,如果你不指定任何其他構造函數被自動創建。由於您用3個參數指定了一個參數,因此您沒有默認構造函數。

有2種方法來解決這個問題:

  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(); 
+0

感謝您的解釋和解決方案。非常感謝。 – Kyle

0

你的錯誤說的是,沒有

PhoneNumber() 

構造函數定義(不PARAMS)。默認情況下,如果你沒有聲明任何其他的構造函數,這就是你在Java中可用的構造函數。但是你通過實施覆蓋它

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

默認(無參數)構造函數只自動爲您如果不定義任何其他構造函數定義。