我的多态性有问题



>有人可以向我解释为什么我在主方法 project5 类时在编码中出现这些错误。 thearray[count++]不断给我错误,我不完全确定我在哪里犯了错误。我已经坚持了一段时间了。一些指导会很好。

这是我的主要方法:

public class Project5 {

private Shape [] thearray = new Shape[100]; 
public static void main (String [] args) {
Project5 tpo = new Project5();
tpo.run();
} 
public void run () {
int count = 0;
thearray[count++] = new Circle(20, 20, 40);
thearray[count++] = new Triangle(70, 70, 20, 30);
thearray[count++] = new Rectangle(150, 150, 40, 40);
for (int i = 0; i < count; i ++ ) {
thearray[i].display(); 
}
int offset = 0;
double totalarea = 0.0;
while (thearray[offset] != null) { 
totalarea = totalarea + thearray[offset].area(); 
offset++;
} 
System.out.println("The total area for " + offset + " Shape objects is     " + totalarea);
} 
}

这是我Circle课:

public class Circle {
private double radius;
public Circle()  {
   radius = 1.0;
}    
public Circle(double newRadius)  {
   radius = 1.0;
   setRadius(newRadius);
}
public void setRadius(double newRadius) {
   if(newRadius > 0) {
   radius = newRadius;
    } 
   else {
       System.out.println("Error: " 
               + newRadius + " is a bad radius value.");
   }
  } 
 public double getRadius()  {
   return radius;
 }
 public double getArea() {
    return radius * radius * Math.PI;
 }
}

这是我的形状类:

abstract class Shape{
int x = 1;
int y = 1;
public int getX() {
return x; 
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y; 
}
public void setY(int y) {
this.y = y;
}
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public void display() {
}
public abstract double area();
}

我会发布我的三角形和矩形类,但我认为这至少足以解释我搞砸的地方。

我查看了您的 Circle 类,构造函数目前只接受一个参数。但是,当您创建圆时,您将指定 3 个参数。

圆可能应该从形状延伸,前两个参数是形状的 x 和 y 位置,对吗?如果是这种情况,请按如下方式更改类:

public class Circle extends Shape {
   private double radius;
   public Circle(int x, int y)  {
      super(x, y);
      radius = 1.0;
   }    
   public Circle(int x, int y, double newRadius)  {
      super(x, y);
      setRadius(newRadius);
   }
   ...etc

最新更新