1 changed files with 65 additions and 0 deletions
@ -0,0 +1,65 @@ |
|||
/** |
|||
* 课后练习w5 基础题(必做) |
|||
* 需求: |
|||
* 1. 定义Shape类,包含draw()方法 |
|||
* 2. 子类Circle、Rectangle重写draw()方法 |
|||
* 3. 编写drawShape(Shape s)方法,调用其draw() |
|||
* 4. 在main方法中测试多态调用 |
|||
*/ |
|||
|
|||
// 父类Shape:定义图形的通用行为
|
|||
class Shape { |
|||
/** |
|||
* 绘制图形的方法,供子类重写 |
|||
*/ |
|||
public void draw() { |
|||
System.out.println("绘制通用图形"); |
|||
} |
|||
} |
|||
|
|||
// 子类Circle:继承Shape,重写draw()
|
|||
class Circle extends Shape { |
|||
@Override |
|||
public void draw() { |
|||
System.out.println("绘制圆形 ⭕"); |
|||
} |
|||
} |
|||
|
|||
// 子类Rectangle:继承Shape,重写draw()
|
|||
class Rectangle extends Shape { |
|||
@Override |
|||
public void draw() { |
|||
System.out.println("绘制矩形 🟦"); |
|||
} |
|||
} |
|||
|
|||
// 主类:包含工具方法和main测试方法
|
|||
public class ShapeTest { |
|||
/** |
|||
* 统一绘制图形的方法,体现多态 |
|||
* @param s 任意Shape类型的图形对象 |
|||
*/ |
|||
public static void drawShape(Shape s) { |
|||
s.draw(); // 自动调用对应子类的draw()方法
|
|||
} |
|||
|
|||
public static void main(String[] args) { |
|||
// 1. 创建不同图形对象
|
|||
Shape circle = new Circle(); |
|||
Shape rectangle = new Rectangle(); |
|||
Shape shape = new Shape(); |
|||
|
|||
// 2. 调用统一方法测试多态
|
|||
System.out.println("===== 图形绘制测试 ====="); |
|||
drawShape(shape); |
|||
drawShape(circle); |
|||
drawShape(rectangle); |
|||
|
|||
// 3. 数组遍历测试(额外补充,体现多态数组用法)
|
|||
System.out.println("\n===== 数组遍历测试 ====="); |
|||
Shape[] shapes = {new Circle(), new Rectangle(), new Shape()}; |
|||
for (Shape s : shapes) { |
|||
drawShape(s); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue