Accessor Methods in Java

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

    With trivial accessor methods, there is no difference except style, but you can also execute code with them, for example:

    public void setName(String name) {
        if (name == null) {
            throw new IllegalArgumentException("Name may not be null");
        }
        this.name = name;
    }
    

    You can also return copies from a getter, thus protecting your data:

    private List middleNames;
    public List getMiddleNames() {
        return new ArrayList(middleNames); // return a copy
        // The caller can modify the returned list without affecting your data
    }
    

    These are just two simple examples, but there are limitless examples of how accessor methods can be used.

    It is better to follow a consistent style, so that's why we always use getters/setters - so code this like may be executed if needed.

提交回复
热议问题