Encapsulation
The instance data of an object should be modified only by that object.(An object should be encapsulated from the rest of
the system.)
需用如下方法才能 调用或修改 private data:
The names of accessor and mutator methods can usually take the form getX and setX, respectively, where X is the name of the value. E.g. getName, setName methods could be used to access and change the variable called name inside an
object。
Visibility modifiers
The effects of public and private visibility
使用private关键字:
注意:若使用该方法,则不需要再用construct进行初始化!
每个成员变量对应一对getter 和 setter(注意布尔类型变量的getter为is)才能访问和修改成员变量。
在其它class里面通过以上方法访问这个Demo类:
自动生成:
Eclips环境:
代码的空白处点右键,或者在Person类名上点右键 —> Source –> Generate Getters and Setters(或直接从菜单进入)
如果是constructor:
空白处点右键,或者在类名上点右键 —> Source –> Generate Constructor using Fields
IDE环境:
也可用于写constructor