Java :Setter Getter and constructor

2019-02-02 06:56发布

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

    public class ExampleClass {

        private int value = 0; 

        public ExampleClass () {
            value = 0; 
        }

        public ExampleClass (int i) {
            this.value = i;
        }

        public int getValue() {
            return value; 
        }

        public void setValue(int val) {
            this.value = val; 
        }

        public static void main(String[] args) {     
            ExampleClass example = new ExampleClass (20);
            example.setValue(20); 
            //Both lines above do same thing - why use constructor? 
            System.out.println(example.getvalue());
        }
   }

All I've learned is that we need getters/setters for security and that they can also be used to change or edit values later on.

My question is that if the constructor is the point of initialization and a default constructor is always present, why use a constructor with parameters to initialize values instead of getters/setters?. Wouldn't using the getter and setter provide security as well being able to easily change values at any stage. Please clarify this point for me.

10条回答
Rolldiameter
2楼-- · 2019-02-02 07:08

Constructor with arguments makes you get the object fully constructed. If you want to use default one, you will have to make sure the fields are set using setters. During set of some property, assume the exception is thrown, now you have an object which is not usable. In several cases, setter wouldn't be exposed but getters. In those cases, having constructor with arguments or a named constructor is the right option. In a nutshell, getters and setters do have their own importance rather than initializing the object.

Why use getters and setters?

查看更多
一夜七次
3楼-- · 2019-02-02 07:10

this is purely upto your coding style. But IMO, I would use parametrized constructor:

  1. to initialize those values which should not be changed. (like username parameter for a person object)

  2. to initialize those values, without setting which, the object will be in invalid state.

Say, you are sending login parameters to a method. You can use in these to ways

Login obj = new Login();
obj.setUsername("user");
obj.setPassword("pw")// what if someone commented this out, or you forget to call it


and otherway,
Login obj = new Login("user", "pw");

while you can send Login object just after setting username in 1st case, it would be invalid at recieving end. but the second method is less prone to bugs, bcz it becomes necessary to pass all the required parameters.

查看更多
\"骚年 ilove
4楼-- · 2019-02-02 07:10

Because you write it using less, more elegant and better readable code when you set the values as parameters in a constructor. Moreover, sometimes some fields are indispensable for the object, so a parameter constructor prevents the user from creating an object omitting necessary fields for the object's functionality. One is though not "oblidged" to call the setters.

查看更多
不美不萌又怎样
5楼-- · 2019-02-02 07:18

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.

查看更多
forever°为你锁心
6楼-- · 2019-02-02 07:20

Sometimes you don't need to set all the fields to specific values at the time of creating. For examle, when you make an array. Also, as already said, it's safer when you use getters -- you can't get nullpointer.

Remember to write the default constructor when you've defined constructor with parameters. Or be sure not to use it.

查看更多
男人必须洒脱
7楼-- · 2019-02-02 07:21

Just to make it easier. It takes less code to use a constructor than to create an object and use the setters.

查看更多
登录 后发表回答