簡體   English   中英

在Java中從派生類調用基類構造函數

[英]Calling a base class constructor from derived class in 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 ???
}
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));
    }
}
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);
    }
}

你的構造函數應該是

public Regularpolygon extends Polygon{

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

// YOUR CODE HERE

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM