Files
oop/lab/lab6/Question6/ManyShapes.java
2022-03-27 18:46:18 +08:00

71 lines
1.7 KiB
Java

/*
* Author: CHEN Yongyuan (Walter) 1930006025 from OOP(1007)
* Date: 2022/03/27
* Description: This is the class for the many shapes.
*/
import java.util.ArrayList;
public class ManyShapes {
private ArrayList<Shape> allShapes;
/**
* Constructor
*/
public ManyShapes() {
this.allShapes = new ArrayList<Shape>();
}
/**
* addShape method takes a shape as argument and adds it to the arraylist.
*
* @param s the shape to be added
*/
public void addShape(Shape s) {
this.allShapes.add(s);
}
/**
* listAllShapes methods print out both the area and the type for each shape in
* the arraylist. For example, if the arraylist currently contains a Square
* object of size 5 and a Dot object the the listAllShapes method should print:
*
* Shape has area 25.0
*
* Shape has area 0.0
*/
public void listAllShapes() {
for (Shape s : this.allShapes) {
String type = "";
if (s instanceof Square) {
type = "Square";
} else if (s instanceof Dot) {
type = "Dot";
} else if (s instanceof Circle) {
type = "Circle";
} else if (s instanceof Rectangle) {
type = "Rectangle";
} else if (s instanceof Shape) {
type = "Shape";
} else if (s instanceof Square) {
type = "Square";
}
System.out.println(String.format("%s has area %f", type, s.area()));
}
}
/**
* Test.
*/
public static void testManyShapes() {
ManyShapes m = new ManyShapes();
m.addShape(new Circle(1.2, 3.4, 4.0)); // Upcast from Circle to Shape.
m.addShape(new Dot(1.2, 3.4)); // Upcast from Dot to Shape.
m.addShape(new Rectangle(1.2, 3.4, 4.0, 5.0)); // Upcast from Rectangle to Shape.
m.addShape(new Shape(1.2, 3.4));
m.addShape(new Square(1.2, 3.4, 5.0)); // Upcast from Square to Shape.
m.listAllShapes();
}
}