How to instantiante object & call setter on same line?

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

    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();
    

提交回复
热议问题