Accessor Methods in Java

后端 未结 8 1415
野趣味
野趣味 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:21

    As a matter of fact it doesn't prevent and there's no difference until you change access modifiers for getter/setter methods or add additional logic into them. The latter not always a good idea but sometimes helps, for example updating the name should force updating some cached value or performing some checks as a result. Using getters/setters are a good practice and used in several approaches like POJOs and JavaBeans but if you are not going to add custom logic into getters/setters and are not going to use these approaches you will be satisfied of using direct access to the fields.

    One thing I'd like to mention. Using getters/setters you can provide computed at the runtime fields that do not exists persistently in the object. For example your Account class's object holds birth date and you need to get the age of it.

提交回复
热议问题