public class Circle {
double radius;
public double area;
public Circle(double r) {
radius = r;
}
public double getRadius() {
return radius;
}
public void setRadius(double r) {
radius = r;
}
public double getArea() {
return /* ??? */;
}
}
class App {
public static void main(String[] args) {
Circle c1 = new Circle(17.4);
c1.area = Math.PI * c1.getRadius() * c1.getRadius();
}
}
The class is poorly encapsulated. You need to change the circle class to compute and return the area instead.
Which two modifications are necessary to ensure that the class is being properly encapsulated?
A. Remove the area field.
B. Change the getArea( ) method as follows:
public double getArea ( ) { return Match.PI * radius * radius; }
C. Add the following method:
public double getArea ( ) {area = Match.PI * radius * radius; }
D. Change the cacess modifier of the SerRadius ( ) method to be protected.
题解
为了让 Circle 类别计算面积的结果不被干扰,我们可以单纯使用 getArea 方法来回传结果值。所以先移除掉 area 字段,接着在 getArea 方法实作面积的算法(πr2)。所以答案是选项 A 和选项 B。
选项 C,会造成编译错误,因为方法有定义回传型态,却没有回传任何数值。
选项 D,将 setRadius 改成使用 protected 修饰,只会让它在不同的套件下,除了子类别之外无法被访问。
