在做java的實驗題時遇到了一個報錯
Implicit super constructor Point() is undefined. Must explicitly invoke another constructor
程序的主要代碼如下:
public class Point { int x, y; //Point(){}//注意這一行
Point(int a, int b){ x = a; y = b; } public double distance() { return Math.sqrt(x*x+y*y); } void print() { System.out.println("This is the superclass!"); } public static void main(String[] args) { // TODO Auto-generated method stub
Point superp = new Point(1,1); System.out.println("superp.distance()="+superp.distance()); superp.print(); Point3d subp = new Point3d(1,1,1); subp.print(); } } class Point3d extends Point{ int z; Point3d(int i, int j, int k){//如果沒有上面注釋的那一行,這里就會報錯 x = i; y = j; z = k; } void print() { System.out.println("This is the subclass!"); } }
我們知道,Point3d繼承了Point,那么在構造Point3d之前,就會先構造Point。
new Point3d的時候用的是默認的構造函數,而子類默認的構造函數調用的也是父類默認的構造函數。
但是父類有了人為指定的構造函數,就覆蓋了本身自動生成的默認無參構造函數,換言之,父類沒有無參構造函數,那么就出錯了。
所以解決辦法是手動再在父類中添加一個無參的與默認構造函數形式相同的構造函數,即:
public class Point { int x, y; Point(){}//注意這一行
Point(int a, int b){ x = a; y = b; }