我的代码有问题(编辑:这些类的整个代码)
public abstract class SimplePolygon implements Polygon {
//protected Vertex2D[] varray; //this is wrong in tests
public double getWidth(){
double min = varray[0].getX(), max = varray[0].getX();
for(int i = 0;i<varray.length;i++){
max = Math.max(max,varray[i].getX());
min = Math.min(min,varray[i].getX());
}
return max - min;
}
public double getHeight(){
double min = varray[0].getY(), max = varray[0].getY();
for(int i = 0;i<varray.length;i++){
max = Math.max(max,varray[i].getY());
min = Math.min(min,varray[i].getY());
}
return max - min;
}
public double getLength(){
double distance = 0;
for(int i = 0;i<varray.length;i++){
if((i+1)<varray.length){distance += varray[i].distance(varray[i+1]);}
else{distance += varray[i].distance(varray[0]);}
}
return distance;
}
public double getArea(){
double suma = 0;
for(int i = 0;i<varray.length-1;i++){
suma += varray[i].getX()*varray[i+1].getY() - varray[i+1].getX()*varray[i].getY();
}
return suma/2;
}
public String toString(){
String str = "Polygon: vertices =";
for(int i = 0;i<varray.length;i++){
str += " ";
str += varray[i];
}
return str;
}
}
public class ArrayPolygon extends SimplePolygon {
public ArrayPolygon(Vertex2D[] array){
varray = new Vertex2D[array.length];
if (array == null){}
for(int i = 0;i<array.length;i++){
if (array[i] == null){}
varray[i] = array[i];
}
}
public Vertex2D getVertex(int index) throws IllegalArgumentException{
return varray[index];
}
public int getNumVertices(){
return varray.length;
}
}
问题是,我不允许向抽象类添加任何属性或方法SimplePolygon
,所以我无法正确初始化varray
。它可以简单地用该类中的受保护属性来解决,但由于某些(愚蠢的)原因我不能这样做。有没有人知道如何解决它?感谢所有帮助。