If I have an Employee
class with a default constructor:
private String firstName;
public Employee(){}
and a setter:
(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.
In order for your code to work, you would have to return the Employee
(meaning "this") in the setter method setFirstName
.
If you don't own the Employee class (I know this is just a simple example - but for the sake of argument) and cannot modify it, one way to solve that is using functional programming. You could declare yourself a function like this:
static final Function<String, Employee> EMPLOYEE = firstName -> {
Employee employee = new Employee();
employee.setFirstName(firstName);
return employee;
};
And then you can create your employee in one line like this:
Employee jake = EMPLOYEE.apply("Jake");
Maybe not exactly what you want, but still useful.
It should be like this:
Employee employee = new Employee();
employee.setFirstName("John");
The method serFirstName
is of return type void
(nothing). Try:
public Employee setFirstName(String fname) {
this.firstName = fname;
return this;
}
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.
Although this is a bit overkill, you could try using the builder pattern
public class Employee{
private String firstName;
public static class Builder{
private String firstName;
public Builder firstName(String firstName){
this.firstName = firstName;
return this;
}
public Employee build(){
return new Employee(this);
}
}
private Employee(Builder builder){
firstName = builder.firstName;
}
}
Then you can do the following
Employee e = new Employee.Builder().firstName("John").build();