首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中从派生类调用基类构造函数

在Java中从派生类调用基类构造函数
EN

Stack Overflow用户
提问于 2010-08-18 01:25:12
回答 3查看 93.6K关注 0票数 37

我有一个如下的类:

代码语言:javascript
复制
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;
    }
}

现在,正多边形是所有边都相等的多边形。我的正多边形的构造器应该是什么?

代码语言:javascript
复制
public Regularpolygon extends Polygon{

//constructor ???
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-08-18 01:29:06

代码语言:javascript
复制
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 class 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));
    }
}
票数 57
EN

Stack Overflow用户

发布于 2013-04-17 17:28:13

代码语言:javascript
复制
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);
    }
}
票数 3
EN

Stack Overflow用户

发布于 2010-08-18 01:30:51

你的构造函数应该是

代码语言:javascript
复制
public Regularpolygon extends Polygon{

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

// YOUR CODE HERE

}

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3505140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档