diff --git a/w4/Shape b/w4/Shape new file mode 100644 index 0000000..6698569 --- /dev/null +++ b/w4/Shape @@ -0,0 +1,38 @@ +// 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); // 输出:绘制矩形 + } +} \ No newline at end of file