在Java中从派生类调用基类构造函数 [英] Calling a base class constructor from derived class in Java

查看:162
本文介绍了在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;
    }
}

现在正多边形是一个多边形,其四面都是等于。我的正多边形的构造函数应该是什么?

Now a regular polygon is a polygon whose all sides are equal. What should be the constructor of my regular polygon?

public Regularpolygon extends Polygon{

//constructor ???
}


推荐答案

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));
    }
}

这篇关于在Java中从派生类调用基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆