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.
45 lines
1.2 KiB
45 lines
1.2 KiB
// 1. 定义父类 Shape
|
|
class Shape {
|
|
// 父类的 draw() 方法,子类可以重写
|
|
public void draw() {
|
|
System.out.println("绘制通用图形");
|
|
}
|
|
}
|
|
|
|
// 2. 定义子类 Circle,继承 Shape,重写 draw()
|
|
class Circle extends Shape {
|
|
@Override
|
|
public void draw() {
|
|
System.out.println("绘制圆形 ⭕");
|
|
}
|
|
}
|
|
|
|
// 3. 定义子类 Rectangle,继承 Shape,重写 draw()
|
|
class Rectangle extends Shape {
|
|
@Override
|
|
public void draw() {
|
|
System.out.println("绘制矩形 🟦");
|
|
}
|
|
}
|
|
|
|
// 4. 主类,包含 drawShape 方法和 main 测试方法
|
|
public class ShapeTest {
|
|
// 多态方法:接收 Shape 类型参数,调用其 draw()
|
|
public static void drawShape(Shape s) {
|
|
s.draw(); // 动态绑定:实际调用传入对象的 draw()
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
// 测试1:传入 Circle 对象
|
|
Shape circle = new Circle();
|
|
drawShape(circle);
|
|
|
|
// 测试2:传入 Rectangle 对象
|
|
Shape rectangle = new Rectangle();
|
|
drawShape(rectangle);
|
|
|
|
// 测试3:直接传入对象(更简洁)
|
|
drawShape(new Circle());
|
|
drawShape(new Rectangle());
|
|
}
|
|
}
|
|
|