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.
18 lines
560 B
18 lines
560 B
// 测试类
|
|
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());
|
|
}
|
|
}
|