插入 object 个元素到 object 数组

Insert object elements to object array

我的任务如下:

public class TestArea 
  {
  public static void main( String args[] ) {
  double side = 5.0 ;  double length = 10.0;    double width = 12.0;
  int size = 5;
  Shape arrayOfShapes[] = new Shape[ size ];

  // fill in your array to reference five various shapes from your 
  // child classes. Include differing data points (i.e., length, width, etc) for each object
  
  /* create a for - enhanced loop to iterate over each arrayofShapes to 
  display the shape name and associated area for each object*/     
  }
}

我不明白应该如何处理 Shape object 数组。我可以轻松地遍历数组,但如何根据任务插入它们?

我的 Parent class 是:

public abstract class Shape
{
   protected String shapeName;

  // abstract getArea method must be implemented by concrete subclasses
  public abstract double getArea();

  public String getName()
  {
    return shapeName;
  }
}

而子class如下:

方形Class:

public class Square extends Shape {
  private double side;
  public Square( double s )
  {
    side = ( s < 0 ? 0 : s );
    shapeName = "Square";
  }

  @Override
  public double getArea() {
    return side*side;
  }
}

矩形class:

public class Rectangle extends Shape{
 private double length, width;
 // constructor
 public Rectangle( double s1, double s2 )
 {
    length = ( s1 < 0 ? 0 : s1 );
    width = ( s2 < 0 ? 0 : s2 );
    shapeName = "Rectangle";
 }

 Override
 public double getArea() {
    return length*width;
 }
}

我未完成的工作在这里:

public class TestArea {
public static void main(String[] args){
    double side = 5.0 ;  double length = 10.0;    double width = 12.0;
    int size = 5;
    Shape arrayOfShapes[] = new Shape[size];
    Square sq= new Square(side);
    Rectangle rt= new Rectangle(length, width);
    // unfinished
    // need help


}
}

将你的形状分配给数组位置:

shapes[0] = sq;
shapes[1] = rt;
// etc

注意:方形 class 应扩展矩形 class;所有正方形都是矩形。