Java :Setter Getter and constructor

前端 未结 11 1281
陌清茗
陌清茗 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 13:13

    My question is that if constructor is point of initialization and default constructor is always there so why we use constructor with parameters to initialize values instead of set get.

    If you think about an object transitioning into different states then it makes sense to have a parameterized constructor alongwith setters and getters. Let me try to put a real life scenario: Think about an Employee class, a new employee joins, you don't know many details but few and you create the object of Employee with defualt and base value of its attributes. You need to register the employee in the system and hence you used the parameterized constructor. Once you get more details about the employee, you use getters and setters to update the attributes.

提交回复
热议问题