Java :Setter Getter and constructor

前端 未结 11 1345
陌清茗
陌清茗 2020-12-25 12:31

I\'m a bit confused about the use of getter/setters and constructors (see the below code for an example)

    public class ExampleClass {

        private in         


        
11条回答
  •  执笔经年
    2020-12-25 12:50

    It's easier and safer to initialize your object variables via your constructor to avoid nullpointers.

    If you instantiate your object without initializing your variables first and you do a get operation on one of your null variables, you might get a nullpointer exception at runtime because you forgot to manually set its value.

    On the flipside of that, if you always initialize your object variables in your default constructor, you have a seriously reduced risk of getting nullpointer exceptions during runtime because none of your variables can be null unless you specifically set them via a setter (which is not recommended).

提交回复
热议问题