2010-08-17 180 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

相关问题