将对象元素插入对象数组



我的任务如下:

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对象数组。我可以很容易地遍历数组,但如何根据任务插入它们?

我的父母班是:

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;
}
}

子类如下:

方形等级:

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;
}
}

矩形类:

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

注意:Square类应该扩展Rectangle类;所有的正方形都是矩形。

最新更新