简体   繁体   中英

Insert object elements to object array

My task is given below:

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*/     
  }
}

I am not understanding what should I do with the Shape object array. I can iterate though the array easily but how can I insert them according to the task?

My Parent class was:

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

And the subclass are given below:

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

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

My unfinished work is here:

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


}
}

Assign your shapes to array locations:

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

Note: Square class should extend Rectangle class; all squares are rectangles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM