You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
939 B
38 lines
939 B
//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); // 输出:画一个矩形
|
|
}
|
|
}
|