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.
33 lines
934 B
33 lines
934 B
// 抽象父类 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("绘制矩形");
|
|
}
|
|
}
|
|
// 工具类/主类
|
|
public class ShapeTest {
|
|
// 统一绘制方法,利用多态
|
|
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); // 输出:绘制矩形
|
|
}
|
|
}
|