1 changed files with 38 additions and 0 deletions
@ -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); // 输出:绘制矩形 |
|||
} |
|||
} |
|||
Loading…
Reference in new issue