Add lab6
This commit is contained in:
70
lab/lab6/Question6/ManyShapes.java
Normal file
70
lab/lab6/Question6/ManyShapes.java
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user