You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.4 KiB

/**
* 测试类:演示多态性
* 通过 drawShape 方法调用不同子类的 draw() 方法
*/
public class TestDrawShape {
/**
* 通用绘制方法:接收任意 Shape 类型的对象
* 利用多态性,自动调用对应子类的 draw() 方法
* @param s Shape 类型的参数
*/
public static void drawShape(Shape s) {
s.draw();
}
/**
* 主方法:程序入口
* @param args 命令行参数
*/
public static void main(String[] args) {
System.out.println("=== 图形绘制测试 ===\n");
// 1. 创建子类对象
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
// 2. 直接调用 draw() 方法
System.out.println("--- 直接调用 draw() ---");
circle.draw();
rectangle.draw();
// 3. 通过 drawShape() 方法调用(体现多态性)
System.out.println("\n--- 通过 drawShape() 方法调用 ---");
drawShape(circle);
drawShape(rectangle);
// 4. 使用父类引用指向子类对象(多态性的典型应用)
System.out.println("\n--- 父类引用指向子类对象 ---");
Shape shape1 = new Circle(3.0);
Shape shape2 = new Rectangle(2.0, 8.0);
drawShape(shape1);
drawShape(shape2);
System.out.println("\n=== 测试完成 ===");
}
}