Accessor Methods in Java

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

    If your code never changes then you're right - there is no difference.

    However, code changes a lot. What happens if you need to keep track of who has modified their name?

    You would need to have a boolean in the Account class that would change to true whenever the name field has changed.

    So now you have to go through every source file and put a

    myAccount.nameChanged = true' under each

    myAccount.name = whatever;

    So you start having code duplication and the possibility for bugs increases. What happens if I missed a name change?

    The best way to counteract this is to have member variables classified as private.

    Your setName code would look something like this:

    public void setName(String newName)
    {
        name = newName;
        nameChanged = true;
    }
    

    And you don't have to worry about bugs!

提交回复
热议问题