Accessor Methods in Java

后端 未结 8 1404
野趣味
野趣味 2021-01-03 06:44

So I have a question on \"setter\" and \"getter\" methods and how useful they are or aren\'t.

Let\'s say I just write a very basic program like the following:

<
8条回答
  •  自闭症患者
    2021-01-03 07:37

    The java keyword "private" in front of each of the Account class’s field declarations, prevents direct reference to that field. If you put myAccount.name = “whatever” in the UseAccount class, you get the error message: "name has private access in Account". Instead of referencing myAccount.name, the UseAccount programmer need to call method myAccount.setName or method myAccount.getName. These methods are called accessor methods, because they provide access to the Account class’s fields.

提交回复
热议问题