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.

44 lines
1.1 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) {
// 测试多态
Shape circle = new Circle();
Shape rectangle = new Rectangle();
Shape shape = new Shape();
drawShape(shape); // 输出:绘制通用图形
drawShape(circle); // 输出:绘制圆形
drawShape(rectangle); // 输出:绘制矩形
}
}