2 changed files with 33 additions and 0 deletions
@ -0,0 +1,33 @@ |
|||
// 抽象父类 Shape
|
|||
abstract class Shape { |
|||
// 抽象方法,由子类实现
|
|||
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 ShapeTest { |
|||
// 统一绘制方法,利用多态
|
|||
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); // 输出:绘制矩形
|
|||
} |
|||
} |
|||
|
After Width: | Height: | Size: 90 KiB |
Loading…
Reference in new issue