下面是繼承Java的繼承示例
的例子class Parent {
Parent(int a, int b) {
int c = a + b;
System.out.println("Sum=" + c);
}
void display() {
System.out.println("Return Statement");
}
}
class Child extends Parent {
Child(int a, int b) {
int c = a - b;
System.out.println("Difference=" + c);
}
}
public class InheritanceExample {
public static void main(String args[]) {
Child c = new Child(2, 1);
c.display();
}
}
時,我沒有非參數化的構造函數的父()
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor
at Child.<init>(InheritanceExample.java:14)
at InheritanceExample.main(InheritanceExample.java:22)
能否請您給我解釋一下,我得到下面的錯誤在基類中沒有參數的構造函數的目的是什麼。
它只是創建父類的一個實例,在這種情況下,默認的構造函數。通常你會將對象變量設置爲某個默認值,或者爲null。 – 2011-05-31 01:35:47
請包括錯誤的_text_,而不是屏幕截圖。 – SLaks 2011-05-31 01:37:47
是真正的源代碼嗎?它通過複製/粘貼編譯並運行良好。 – TofuBeer 2011-05-31 01:44:24