commit
15d177f1a2
1 changed files with 41 additions and 0 deletions
@ -0,0 +1,41 @@ |
|||||
|
// 父类 Shape
|
||||
|
class Shape { |
||||
|
// 父类 draw 方法,子类重写
|
||||
|
public void draw() { |
||||
|
System.out.println("绘制通用图形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 子类 Circle,重写 draw 方法
|
||||
|
class Circle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制圆形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 子类 Rectangle,重写 draw 方法
|
||||
|
class Rectangle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制矩形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 主类,包含 drawShape 方法和 main 方法
|
||||
|
public class ShapeTest { |
||||
|
// 多态方法:接收 Shape 类型参数,调用其 draw 方法
|
||||
|
public static void drawShape(Shape s) { |
||||
|
s.draw(); |
||||
|
} |
||||
|
|
||||
|
// main 方法,程序入口
|
||||
|
public static void main(String[] args) { |
||||
|
// 测试:创建子类对象,传入 drawShape 方法
|
||||
|
Shape circle = new Circle(); |
||||
|
Shape rectangle = new Rectangle(); |
||||
|
|
||||
|
drawShape(circle); |
||||
|
drawShape(rectangle); |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue