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 都與封裝概念沒有太大的關聯。