Do objects encapsulate data so that not even other instances of the same class can access the data?

前端 未结 7 1665
梦如初夏
梦如初夏 2020-12-03 22:35

In Java,

Do objects encapsulate data so that not even other instances of the same class can access the data? Only when the keyword \"private\" is used? What are \"ac

7条回答
  •  广开言路
    2020-12-03 23:02

    No, private fields can be accessed even from other instances (within a method of the same class).

    They cannot be accessed from subclasses, however, not even within the same instance.

    You provide getter methods to allow "outside" code to access fields in your class. Since it is up to you what getters you provide, how visible you make them, and how they are implemented, you can exercise a lot of control as to who can access the data and how.

    Note that there does not really need to be a name field if there is a getName: it is entirely up to the implementation of the getter where that data comes from.

    Even if the getter (or setter) just wraps a private field, it is good style to have these setters and getters (as opposed to allowing direct field access).

提交回复
热议问题