2011-12-14 29 views
-2

爲什麼不能編譯這個類?我的班級定義有什麼問題?

class Exam { 

private int score; 

    // constructor initializes score to 99 
    public void Exam() { 
     score = 99; 
    } 

    // returns the current value of score 
    private int getScore() { 
     return score; 
    } 

    // returns the String representation of the Object 
    public String toString() { 
     return "The score is " + getScore(); 
    } 
} 
+2

什麼錯誤信息你好嗎? – 2011-12-14 21:33:35

+1

爲什麼不與我們分享編譯器的錯誤信息? – Codo 2011-12-14 21:34:17

回答

7

你的構造函數不應該有返回類型。甚至無效。

public Exam() { 
    score = 99; 
} 
3

的構建體不應該包含void關鍵字:

public Exam() { 
    score = 99; 
} 

構造函數返回一個引用該新創建的對象。但是你不必寫它。所以認爲它是void也是錯誤的。

2

構造函數不需要返回類型。刪除無效,你應該設置。

1

在您不使用void構造。

寫的構造函數:

public Exam() { 
    score = 99; 
} 
0

的主要問題是缺少包聲明。

package yourpkg; 

class Exam { 

此外,在爲Exam()返回類型使得它的功能,而不是一個構造函數和將導致一個警告。

0

只是沒有涉及到具體問題的建議:

private int score; 

// returns the current value of score 
private int getScore() { 
    return score; 
} 

有一個在具有getScore()如果你要保持它private沒有意義的。做它public

而且,經常使用@Override註釋只要你的意圖是覆蓋一些方法。如果你沒有這樣做,編譯器會讓你知道。這意味着錯誤預防。

例如

// returns the String representation of the Object 
@Override 
public String toString() { 
    return "The score is " + getScore(); 
}