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