我给了一个类PolyShape通过它们的边数表示多边形,并且包含它们的边长的数组,我必须将它扩展为一个称为四边形的类,它代表一个有4边的多边形。我不确定如何处理这个问题。我启动了程序,但有人可以帮我解释一下我应该包括在数组方面我应该如何使用VarArgs吗?
import java.util.Arrays;
public class PolyShape {
private int numSides;
private int[] sideLengths;
public PolyShape(int ... sideLengths) {
this.sideLengths = sideLengths;
this.numSides = sideLengths.length;
}
public int getNumSides() {
return numSides;
}
public int[] getSideLengths() {
return Arrays.copyOf(sideLengths, sideLengths.length);
}
public int getPerimeter() {
int perim = 0;
for(int n : sideLengths)
perim += n;
return perim;
}
public String toString() {
String s = "I am a shape with " + numSides + " sides of length: ";
for(int length : sideLengths)
s += length + " ";
s += "\nI am a polygon.";
return s;
}
}
四边形课程:
public class Quadrilateral extends PolyShape {
private final int POLYGON_SIDES = 4;
public Quadrilateral(int ... sideLengths) {
super(sideLengths);
}
public String toString() {
String parentString = super.toString();
parentString += "\nI am a Quadrilateral.";
return parentString;
}
}
答案 0 :(得分:0)
您的子类是Quadrilateral,它有4个边,因此您不需要使用vararg方法参数创建构造函数。只需在构造函数中传递4个边。将这4个方面传递给父构造函数肯定会使用vararg参数调用父构造函数。
答案 1 :(得分:0)
public Quadrilateral extends PolyShape {
public Quadrilateral(int side1, int side2, int side3, int side4) {
super(side1, side2, side3, side4);
}
}