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 都与封装概念没有太大的关联。