2010-08-17 246 views
31

我有一個類如下:從調用派生類的基類構造函數在Java中

public class Polygon extends Shape{ 

    private int noSides; 
    private int lenghts[]; 

    public Polygon(int id,Point center,int noSides,int lengths[]) { 
     super(id, center); 
     this.noSides = noSides; 
     this.lenghts = lengths; 
    } 
} 

現在正多邊形是多邊形,其四面都是平等的。我的正多邊形的構造函數應該是什麼?

public Regularpolygon extends Polygon{ 

//constructor ??? 
} 
+1

很高興你接受這一個。但之前您已經提出了更多問題。如果你似乎無法找到它們,只需點擊任何你的名字出現的鏈接(例如,在頂欄或上面的「問」框中),然後你將登陸你的[個人資料頁面](http: //stackoverflow.com/users/419373/akshay)。你可以在那裏找到你所有的歷史,包括你之前問過的問題。 PS:註冊您的帳戶會很好,否則您將無法在其他PC /瀏覽器上登錄相同的帳戶。 – BalusC 2010-08-17 17:51:36

回答

50
public class Polygon extends Shape {  
    private int noSides; 
    private int lenghts[]; 

    public Polygon(int id,Point center,int noSides,int lengths[]) { 
     super(id, center); 
     this.noSides = noSides; 
     this.lenghts = lengths; 
    } 
} 

public RegularPolygon extends Polygon { 
    private static int[] getFilledArray(int noSides, int length) { 
     int[] a = new int[noSides]; 
     java.util.Arrays.fill(a, length); 
     return a; 
    } 

    public RegularPolygon(int id, Point center, int noSides, int length) { 
     super(id, center, noSides, getFilledArray(noSides, length)); 
    } 
} 
2

你的構造應該是

public Regularpolygon extends Polygon{ 

public Regularpolygon (int id,Point center,int noSides,int lengths[]){ 
super(id, center,noSides,lengths[]); 

// YOUR CODE HERE 

} 

} 
+5

我不得不爲-1,因爲在基類中提供無參數構造函數是很好的編碼習慣。 – 2010-08-17 17:39:05

1
class Foo { 
    Foo(String str) { } 
} 

class Bar extends Foo { 
    Bar(String str) { 
     // Here I am explicitly calling the superclass 
     // constructor - since constructors are not inherited 
     // you must chain them like this. 
     super(str); 
    } 
} 
+0

我認爲這個問題是不同的。你不知何故錯過了這一點。 – 2013-04-17 09:49:12

相關問題