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 修飾,只會讓它在不同的套件下,除了子類別之外無法被存取。