5 changed files with 99 additions and 0 deletions
@ -0,0 +1,66 @@ |
|||
// 抽象图形类
|
|||
abstract class Shape { |
|||
public abstract double getArea(); |
|||
} |
|||
|
|||
// 圆形类
|
|||
class Circle extends Shape { |
|||
private double radius; |
|||
|
|||
public Circle(double radius) { |
|||
this.radius = radius; |
|||
} |
|||
|
|||
@Override |
|||
public double getArea() { |
|||
return Math.PI * radius * radius; |
|||
} |
|||
} |
|||
|
|||
// 矩形类
|
|||
class Rectangle extends Shape { |
|||
private double width; |
|||
private double height; |
|||
|
|||
public Rectangle(double width, double height) { |
|||
this.width = width; |
|||
this.height = height; |
|||
} |
|||
|
|||
@Override |
|||
public double getArea() { |
|||
return width * height; |
|||
} |
|||
} |
|||
|
|||
// 三角形类
|
|||
class Triangle extends Shape { |
|||
private double base; |
|||
private double height; |
|||
|
|||
public Triangle(double base, double height) { |
|||
this.base = base; |
|||
this.height = height; |
|||
} |
|||
|
|||
@Override |
|||
public double getArea() { |
|||
return 0.5 * base * height; |
|||
} |
|||
} |
|||
|
|||
// 工具类
|
|||
class ShapeUtil { |
|||
public static void printArea(Shape shape) { |
|||
System.out.printf("面积:%.2f%n", shape.getArea()); |
|||
} |
|||
} |
|||
|
|||
// 主类(程序入口)
|
|||
public class Main { |
|||
public static void main(String[] args) { |
|||
ShapeUtil.printArea(new Circle(5)); |
|||
ShapeUtil.printArea(new Rectangle(4, 6)); |
|||
ShapeUtil.printArea(new Triangle(3, 4)); |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
实验报告 |
|||
1. 实验目的 |
|||
通过抽象类和继承重构图形面积计算器,实现代码的复用、扩展和统一管理。 |
|||
2. 实验步骤 |
|||
设计抽象类Shape,定义抽象方法getArea() |
|||
编写Circle/Rectangle/Triangle继承Shape,实现各自的面积计算 |
|||
编写工具类ShapeUtil,提供统一的printArea方法 |
|||
绘制 UML 类图 |
|||
分析组合与继承的区别,完成实验反思 |
|||
3.AI使用情况 |
|||
AI帮助完成并修改代码 |
|||
`public` 类只能有一个:一个文件里只能有一个 `public` 类,其他类必须是默认访问权限(不加修饰符) |
|||
将文件命名为Shape而无法运行,询问AI并指出应修改为Main,与类名保持一致 |
|||
询问AI进一步了解组合,继承,多态 |
|||
4.组合vs继承 |
|||
此次代码使用的是继承,这是典型的 is-a 关系:圆形 是一个 图形、矩形 是一个 图形。 |
|||
继承适合层级明确、逻辑统一的场景,能很好体现多态(AI总结为多态是面向对象的三大特性之一,指父类引用可以指向子类对象,在调用同名方法时,会根据实际对象类型执行对应子类的实现,呈现出不同行为) |
|||
|
|||
继承:是一种(is‑a)继承:学生 是一个 人 → Student extends Person |
|||
组合:有一个(has‑a)组合:电脑 有一个 屏幕 → Computer { private Screen screen; } |
|||
继承实现方式:子类继承抽象父类,重写抽象方法 |
|||
组合实现:把其他类对象作为成员变量 |
|||
|
|||
继承的特点有: |
|||
结构清晰,符合现实逻辑(图形→具体图形) |
|||
利用多态:Shape shape = new Circle(…) |
|||
代码复用:统一接口 getArea() |
|||
扩展方便:新增图形只需新增子类,不改动原有代码 |
|||
|
|||
组合的特点有: |
|||
耦合度低,更灵活 |
|||
不受 Java 单继承限制 |
|||
方便复用多个类的功能 |
|||
|
After Width: | Height: | Size: 4.5 MiB |
|
After Width: | Height: | Size: 399 KiB |
Loading…
Reference in new issue