diff --git a/w5 b/w5 new file mode 100644 index 0000000..c1f0201 --- /dev/null +++ b/w5 @@ -0,0 +1,37 @@ +// 定义Shape类 +abstract class Shape { + // draw方法,由子类重写 + public abstract void draw(); +} + +// Circle子类 +class Circle extends Shape { + @Override + public void draw() { + System.out.println("画一个圆形 ⚪"); + } +} + +// Rectangle子类 +class Rectangle extends Shape { + @Override + public void draw() { + System.out.println("画一个矩形 ▭"); + } +} + +public class Main { + // 编写drawShape方法,接收Shape类型参数 + public static void drawShape(Shape s) { + s.draw(); // 多态调用实际子类的draw方法 + } + + public static void main(String[] args) { + // 测试 + Shape circle = new Circle(); + Shape rectangle = new Rectangle(); + + drawShape(circle); // 输出:画一个圆形 ⚪ + drawShape(rectangle); // 输出:画一个矩形 ▭ + } +} \ No newline at end of file