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.

37 lines
870 B

// 定义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); // 输出:画一个矩形 ▭
}
}