2 changed files with 38 additions and 0 deletions
@ -0,0 +1,20 @@ |
|||||
|
class Shape { |
||||
|
public void draw() { |
||||
|
System.out.println("绘制一个形状"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
class Circle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制一个圆形 ○"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
class Rectangle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制一个矩形 ▭"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
@ -0,0 +1,18 @@ |
|||||
|
// 测试类
|
||||
|
public class TestShape { |
||||
|
// 多态方法:接收父类引用,实际调用子类重写的方法
|
||||
|
public static void drawShape(Shape s) { |
||||
|
s.draw(); // 这里发生多态
|
||||
|
} |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
Shape s1 = new Circle(); // 向上转型
|
||||
|
Shape s2 = new Rectangle(); |
||||
|
|
||||
|
drawShape(s1); // 输出:绘制一个圆形 ○
|
||||
|
drawShape(s2); // 输出:绘制一个矩形 ▭
|
||||
|
|
||||
|
// 直接用子类对象也可以
|
||||
|
drawShape(new Circle()); |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue