1 changed files with 37 additions and 0 deletions
@ -0,0 +1,37 @@ |
|||||
|
// 定义Shape类 |
||||
|
abstract class Shape { |
||||
|
// draw方法,由子类重写 |
||||
|
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 Main { |
||||
|
// 编写drawShape方法,接收Shape类型参数 |
||||
|
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); // 输出:画一个矩形 ▭ |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue