1 changed files with 38 additions and 0 deletions
@ -0,0 +1,38 @@ |
|||||
|
//TIP 要<b>运行</b>代码,请按 <shortcut actionId="Run"/> 或
|
||||
|
// 点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
|
||||
|
// 基类 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("画一个矩形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 测试类
|
||||
|
class TestPolymorphism { |
||||
|
// 接收 Shape 类型参数,调用其 draw 方法
|
||||
|
public static void drawShape(Shape s) { |
||||
|
s.draw(); |
||||
|
} |
||||
|
|
||||
|
static void main() { |
||||
|
Shape circle = new Circle(); |
||||
|
Shape rectangle = new Rectangle(); |
||||
|
|
||||
|
drawShape(circle); // 输出:画一个圆形
|
||||
|
drawShape(rectangle); // 输出:画一个矩形
|
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue