本文详解如何为 Circle 类设计 add(Circle other) 方法,使其将当前圆与另一圆的面积相加,并自动更新自身半径,使新圆面积等于两圆面积之和,同时支持链式调用。
本文详解如何为 circle 类设计 `add(circle other)` 方法,使其将当前圆与另一圆的面积相加,并自动更新自身半径,使新圆面积等于两圆面积之和,同时支持链式调用。
在面向对象编程中,add 方法不应简单理解为“数值相加”,而应体现领域语义——本题明确要求:两个圆的“相加”定义为生成一个新圆,其面积等于原两圆面积之和。由于圆面积公式为 $A = \pi r^2$,因此若原半径分别为 $r_1$ 和 $r2$,目标半径 $r{\text{new}}$ 需满足:
$$ \pi r_{\text{new}}^2 = \pi r_1^2 + \pi r2^2 \quad \Rightarrow \quad r{\text{new}} = \sqrt{r_1^2 + r_2^2} $$
可见,$\pi$ 在计算中可被约去,无需显式参与(但保留亦无错,仅略失简洁)。
正确实现 add 方法
add 方法需满足以下关键设计原则:
- 参数类型严格为 Circle:不可写作 add(double circle),因题干明确要求“a Circle object as its only parameter”;
- 返回 this(即当前 Circle 实例):以支持链式调用(如 c1.add(c2).add(c3));
- 就地修改当前对象状态(mutating):直接更新 this.radius,而非创建新对象;
- 访问权限合理:radius 应设为 private,通过 getRadius() 封装读取,符合封装原则。
以下是符合所有要求、经测试验证的完整实现:
public class Circle {
private double radius;
private static final double PI = Math.PI; // 使用 static final 更合理
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
/**
* 将当前圆与参数圆的面积相加,并更新当前圆的半径,
* 使新面积等于二者面积之和。
* 支持链式调用。
*/
public Circle add(Circle other) {
if (other == null) {
throw new IllegalArgumentException("Cannot add null Circle");
}
// 面积和 = π*r₁² + π*r₂² → 新半径² = r₁² + r₂²
double newRadiusSquared = this.radius * this.radius + other.radius * other.radius;
this.radius = Math.sqrt(newRadiusSquared);
return this; // 返回 this 以支持链式调用
}
}关键注意事项
- ✅ 链式调用依赖 return this:c1.add(c2).add(c3) 能成立,正是因为每次 add() 都返回修改后的 c1 本身;若返回 void 或新对象,则链式失效。
- ❌ 原始代码存在类型错误:问题中示例 return this.radius; 返回的是 double,但方法声明为 public Circle add(...),编译不通过——必须返回 Circle 类型(即 return this;)。
- ⚠️ 避免副作用混淆:该 add 是变异式(mutating)操作,仅修改调用者(如 c1),不改变参数对象(c2, c3 保持原半径)。输出结果中仅 c1 半径变化,印证此设计。
- ? 健壮性增强:添加 null 检查,防止运行时 NullPointerException,体现工业级编码习惯。
运行验证
配合题干提供的 TestCircle 主类,执行后输出与预期完全一致:
Before adding, Radius of the first circle is 3.5 Radius of the second circle is 6.8 Radius of the third circle is 12.9 After adding, Radius of the first circle is 14.996666296213968 Radius of the second circle is 6.8 Radius of the third circle is 12.9
计算验证:
$\sqrt{3.5^2 + 6.8^2 + 12.9^2} = \sqrt{12.25 + 46.24 + 166.41} = \sqrt{224.9} \approx 14.9967$ —— 精确吻合。
综上,add 方法的本质是几何面积的代数合成,其实现需紧扣数学定义、语言规范与面向对象契约。掌握此类“语义化方法设计”,是写出清晰、可靠、可演化的 Java 类的关键一步。










