Given the definition of the Vehicle class:



class Vehicle {

    String name;

    void setName(String name) {
        this.name = name;
    }

    String getName() {
        return name;
    }
}

Which action encapsulates the Vehicle class?

A. Make the Vehicle class public.
B. Make the name variable public.
C. Make the setName method public.
D. Make the name variable private.
E. Make the setName method private.
F. Make the getName method private.

題解

封裝的概念在於保護程式碼,以及物件的欄位資料的正確性。

選項A,與封裝的概念無關。

選項B,與封裝的概念背道而馳。應將name欄位設成private可見度後,使用getter和setter來存取name欄位的資料。

選項C,setName方法是不是public都與封裝概念沒有太大的關聯。

選項D,正確。

選項E,setName方法是不是private都與封裝概念沒有太大的關聯。

選項F,getName方法是不是private都與封裝概念沒有太大的關聯。