How to instantiante object & call setter on same line?

前端 未结 8 1284
一个人的身影
一个人的身影 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.

提交回复
热议问题