How to instantiante object & call setter on same line?

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

    You can also use this syntax:

    Employee employee = new Employee() {{
        setFirstName("John");
    }};
    

    Though keep in mind that it's going to create an anonymous inner class and probably isn't what you want.

提交回复
热议问题