#java #arrays #polymorphism
Вопрос:
Моя задача приведена ниже:
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
}
}
Ответ №1:
Назначьте свои фигуры местоположениям массива:
shapes[0] = sq;
shapes[1] = rt;
// etc
Примечание: Класс Square должен расширять класс Rectangle; все квадраты являются прямоугольниками.