2015-04-03 49 views
2

我已經編寫了以下Java程序。但是我不斷收到一個錯誤,說我的構造函數的實際和形式參數長度不同。我不明白問題是什麼。有人可以告訴我我的程序有什麼問題,以及我可以如何調試它?Java錯誤 - 實際和正式參數列表的長度不同

class Student 
{ 
String name; 
Student(String name) 
{ 
    System.out.println("\nThe name of the student is:"+name); 
} 
} 
class Exam extends Student 
{ 
int m1, m2; 
Exam(int m1, int m2) 
{ 
    System.out.println("\nThe marks obtained in first subject is:"+m1); 
    System.out.println("\nThe marks obtained in second subject is:"+m2); 
} 
} 
class Result extends Exam 
{ 
int totalmarks; 
int compute(int m1, int m2) 
{ 
    totalmarks=m1+m2; 
    return(totalmarks); 
} 
} 
public class StudentTest 
{ 
public static void main(String[] args) 
{ 
    Student s = new Student("rose"); 
    Exam e = new Exam(20,20); 
    Result r = new Result(); 
    System.out.println("\nThe total marks obtained is:"+r.compute(20,20)); 
} 
} 
+0

要麼使默認的構造函數只添加超(null);語句作爲考試構造函數中的第一條語句。 – Nimesh 2015-04-03 08:00:44

回答

2

解決你的問題,你應該刪除不必要的遺產:

// remove extends Student 
class Exam { 
    // class code here 
} 

// remove extends Exam 
class Result { 
    // class code here 
} 

鑑於你的班,我沒有看到一個原因Exam延長StudentResult延長Exam

認爲extends是「是」的關係。如果您能說ExamStudent而且ResultExam您應該延長。在這種情況下沒有意義。

當一個類繼承另一個,和構造函數被調用,它需要做的第一件事就是打電話給構造。如果你不自己調用它,它會隱式調用。問題是它試圖調用默認的構造函數,但是默認的構造函數只有在你不創建自己的構造函數時纔會被創建。

所以,當你這樣做:

new Exam(20, 20) 

它確實真的:

Exam(int m1, int m2) { 
    super(); // implicit call to Student default constructor 
    System.out.println("\nThe marks obtained in first subject is:"+m1); 
    System.out.println("\nThe marks obtained in second subject is:"+m2); 
} 

它試圖調用默認的無參數的構造函數Student()。但是由於您創建了Student(String name),因此缺省值不存在。這就是你得到錯誤的原因。

+0

「但默認構造函數只有在您不創建自定義構造函數時才存在」:實際上,這只是部分爲真。這只是如此,如果有另一個構造函數(非默認)提供。 – Stultuske 2015-04-03 07:04:19

+0

是的,這就是爲什麼我說默認構造函數只存在如果你不創建自定義構造函數。 – 2015-04-03 07:05:19

+0

再次,這是不正確的。 public class A {} 在這裏,我沒有創建自定義構造函數,但它確實存在。 – Stultuske 2015-04-03 07:05:56

0

定義在學生非參數的構造函數和考試

在Student類:

Student(){ 
    //Give your implementation 
} 

在考試類:

Exam(){ 
    //Give your implementation 
} 
1

你的問題是你的層次結構。執行構造函數的第一步是運行父類的默認構造函數。

考試擴展了學生,但學生沒有默認的構造函數。加一個。

更好的是,重新思考你的邏輯。考試擴展學生根本沒有意義。 考試由學生完成。你是說考試是一名學生。

相關問題