所以我正在用java为学校做作业......这是一种类层次结构的作业,我们应该制作一个“Triangle.java”类,它扩展了一个“ClosedShape.java”类,它扩展了一个“Shape.java” ” .... ClosedShape 和 Shape 都是给我们的,所以很可能它们没有问题(无论如何我都会发布它们),但我的 Triangle 类如下:
public abstract class Triangle extends ClosedShape{
public Triangle(int[] a, int[] b, int base, int height){
super(true, 3, a, b);
setWidth(base);
setHeight(height);
setXYCoords(a, b);
}
public Triangle(int x, int y, int base, int height){
int[] a = new int[3];
int[] b = new int[3];
a[0] = x;
a[1] = (x+base)/2;
a[2] = (x+base);
b[0] = y;
b[1] = (y+height)/2;
b[2] = (y+height);
}
}
我有两个构造函数的原因是因为我需要创建这两个数组来保存绘制形状的点......然后我需要将它们传递给 ClosedShape(boolean, int, int[], int[])超级类...如果我在同一个构造函数中创建数组,则需要在调用 super() 之前定义它们,以便可以传入它们,但这是不允许的,因为必须首先调用 super()。 .so 目前,当我尝试编译 Triangle.java 时出现错误:
Triangle.java.14: error: no suitable constructor found for ClosedShape()
{ //little arrow pointing under the '{'
constructor ClosedShape.ClosedShape(boolean, int, int[], int[]) is not applicable
(actual and formal argument lists differ in length)
constructor ClosedShape.ClosedShape(boolean, int) is not applicable
(actual and formal argument lists differ in length)
1 error
它还在分配中指定三角形的签名必须是 Traingle(int x, int y, int base, int height)...所以....我很困惑,因为如果我没记错的话(哪个 java相信我......)我用所有正确的值进行了超级调用,并且有一个构造函数“ClosedShape(boolean,int,int [],int [])”......继承了ClosedShape类:
import java.awt.Graphics;
public abstract class ClosedShape extends Shape {
boolean polygon;
int numPoints;
int[] xVertices;
int[] yVertices;
int x,y,width, height;
public ClosedShape(boolean isPolygon, int numPoints) {
super(0,0);
this.polygon = isPolygon;
this.numPoints = numPoints;
}
public ClosedShape(boolean isPolygon, int numPoints, int[] x, int[] y) {
super(x[0],y[0]);
this.polygon = isPolygon;
if (isPolygon) {
this.numPoints = numPoints;
xVertices = new int[numPoints]; // error check? if x.length == numPoints
//for (int i = 0; i < x.length; i++) { // make copy of array: why?
// xVertices[i] = x[i];
//}
yVertices = new int[numPoints]; // error check? if y.length == numPoints
for (int i = 0; i < y.length; i++) { // make copy of array
yVertices[i] = y[i];
}
}
else { // its an oval - define bounding box
this.numPoints = 4;
this.x = x[0];
this.y = y[0];
width = x[1];
height = y[1];
}
}
public void setXYCoords(int[] x, int[] y){
this.xVertices = x;
this.yVertices = y;
}
// Gives access to the width attribute
public void setWidth(int width){
this.width = width;
}
// Gives access to the height attribute
public void setHeight(int height) {
this.height = height;
}
public void draw(Graphics g) {
if (polygon) {
g.drawPolygon(xVertices, yVertices, numPoints);
}
else {
g.drawOval(x, y, width, height);
}
}
public abstract double Area();
public abstract double Perimeter();
}