3 changed files with 48 additions and 0 deletions
@ -0,0 +1,31 @@ |
|||||
|
// 1. 定义父类 Shape1
|
||||
|
class Shape1 { |
||||
|
// 父类的 draw 方法
|
||||
|
public void draw() { |
||||
|
System.out.println("绘制形状"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 2. 定义子类 Circle 继承 Shape1 并重写 draw 方法
|
||||
|
class Circle extends Shape1 { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制圆形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 3. 定义子类 Rectangle 继承 Shape1 并重写 draw 方法
|
||||
|
class Rectangle extends Shape1 { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制矩形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 4. 定义工具类,包含 drawShape 方法
|
||||
|
class ShapeDrawer { |
||||
|
// 接收 Shape1 类型参数,调用 draw 方法
|
||||
|
public void drawShape(Shape1 s) { |
||||
|
s.draw(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,17 @@ |
|||||
|
// 5. 主类,包含 main 方法进行测试
|
||||
|
public class ShapeTest { |
||||
|
public static void main(String[] args) { |
||||
|
// 创建对象
|
||||
|
Shape1 circle = new Circle(); |
||||
|
Shape1 rectangle = new Rectangle(); |
||||
|
Shape1 generalShape = new Shape1(); |
||||
|
|
||||
|
// 创建工具类对象
|
||||
|
ShapeDrawer drawer = new ShapeDrawer(); |
||||
|
|
||||
|
// 调用 drawShape 方法,体现多态
|
||||
|
drawer.drawShape(generalShape); // 输出:绘制形状
|
||||
|
drawer.drawShape(circle); // 输出:绘制圆形
|
||||
|
drawer.drawShape(rectangle); // 输出:绘制矩形
|
||||
|
} |
||||
|
} |
||||
|
After Width: | Height: | Size: 288 KiB |
Loading…
Reference in new issue