How to instantiante object & call setter on same line?

前端 未结 8 1281
一个人的身影
一个人的身影 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:22

    (employee = new Employee()).setFirstName("John");
    

    performs instantiation and calling the setter, as you requested in the headline, but does not declare the variable as suggested in your code example.

    (Employee employee = new Employee()).setFirstName("John");
    

    will probably not work, I assume. But you can try.

    Of course, you can always stuff multiple statements in one line.

    Employee employee; (employee = new Employee()).setFirstName("John");
    

    or

    Employee employee = new Employee(); employee.setFirstName("John");
    

    If I were you, I would settle for a parameterized constructor, though.

提交回复
热议问题