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.
 
 

38 lines
930 B

// Shape 类(父类)
abstract class Shape {
public abstract void draw(); // 抽象方法,子类必须实现
}
// Circle 类(继承 Shape)
class Circle extends Shape {
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
// Rectangle 类(继承 Shape)
class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
// 测试类
public class TestShape {
// 方法:接收 Shape 对象并调用其 draw 方法
public static void drawShape(Shape s) {
s.draw();
}
public static void main(String[] args) {
// 创建不同形状对象
Shape circle = new Circle();
Shape rectangle = new Rectangle();
// 调用 drawShape 方法测试多态
drawShape(circle); // 输出:绘制圆形
drawShape(rectangle); // 输出:绘制矩形
}
}