Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiante object & call setter on same line?

Tags:

If I have an Employee class with a default constructor:

private String firstName; public Employee(){} 

and a setter:

public void setFirstName(String firstName){     this.firstName = firstName; } 

Why does this attempt fail to instantiate and call the setter in the same line?

Employee employee = new Employee().setFirstName("John"); 
like image 866
Tigmal Avatar asked Jun 13 '11 19:06

Tigmal


1 Answers

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.

like image 75
stevevls Avatar answered Sep 17 '22 18:09

stevevls