How to instantiante object & call setter on same line?

前端 未结 8 1283
一个人的身影
一个人的身影 2020-12-10 10:49

If I have an Employee class with a default constructor:

private String firstName;
public Employee(){}

and a setter:

         


        
相关标签:
8条回答
  • 2020-12-10 11:31

    Because the you want to set employee to the value of .setFirstName("John"); which does not return anything because it is a void

    So you could either change your setter to:

    public Employee setFirstName(String fname) {
      this.firstName = fname;
      return this;
    }
    

    OR Create a second constructor for Employee

    public Employee(String fname){this.firstName = fname;}
    

    Which would set firstname on init.

    0 讨论(0)
  • 2020-12-10 11:40

    Because setFirstName doesn't return anything. If you want to chain methods then setFirstName would have to return Employee.

    Another approach is to have a constructor that takes firstName as an argument.

    0 讨论(0)
提交回复
热议问题