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.
41 lines
985 B
41 lines
985 B
// 父类 Shape
|
|
class Shape {
|
|
// 父类 draw 方法,子类重写
|
|
public void draw() {
|
|
System.out.println("绘制通用图形");
|
|
}
|
|
}
|
|
|
|
// 子类 Circle,重写 draw 方法
|
|
class Circle extends Shape {
|
|
@Override
|
|
public void draw() {
|
|
System.out.println("绘制圆形");
|
|
}
|
|
}
|
|
|
|
// 子类 Rectangle,重写 draw 方法
|
|
class Rectangle extends Shape {
|
|
@Override
|
|
public void draw() {
|
|
System.out.println("绘制矩形");
|
|
}
|
|
}
|
|
|
|
// 主类,包含 drawShape 方法和 main 方法
|
|
public class ShapeTest {
|
|
// 多态方法:接收 Shape 类型参数,调用其 draw 方法
|
|
public static void drawShape(Shape s) {
|
|
s.draw();
|
|
}
|
|
|
|
// main 方法,程序入口
|
|
public static void main(String[] args) {
|
|
// 测试:创建子类对象,传入 drawShape 方法
|
|
Shape circle = new Circle();
|
|
Shape rectangle = new Rectangle();
|
|
|
|
drawShape(circle);
|
|
drawShape(rectangle);
|
|
}
|
|
}
|