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.2 KiB

// 父类 Shape
class Shape {
// 父类的 draw 方法,供子类重写
public void draw() {
System.out.println("绘制通用图形");
}
}
// 子类 Circle 继承 Shape
class Circle extends Shape {
// 重写 draw 方法,实现圆形的绘制逻辑
@Override
public void draw() {
System.out.println("绘制圆形 ⭕");
}
}
// 子类 Rectangle 继承 Shape
class Rectangle extends Shape {
// 重写 draw 方法,实现矩形的绘制逻辑
@Override
public void draw() {
System.out.println("绘制矩形 🟦");
}
}
// 测试类
public class ShapeTest {
// 多态核心方法:接收 Shape 类型参数,自动调用对应子类的 draw()
public static void drawShape(Shape s) {
s.draw();
}
public static void main(String[] args) {
// 1. 创建不同子类对象
Shape circle = new Circle();
Shape rectangle = new Rectangle();
Shape shape = new Shape();
// 2. 调用统一方法,触发多态
System.out.println("=== 基础题测试 ===");
drawShape(shape); // 调用父类 draw()
drawShape(circle); // 调用 Circle 的 draw()
drawShape(rectangle); // 调用 Rectangle 的 draw()
}
}