When should I use “this” in a class?

后端 未结 18 2185
情书的邮戳
情书的邮戳 2020-11-21 23:36

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x i

18条回答
  •  逝去的感伤
    2020-11-22 00:03

    this is useful in the builder pattern.

    public class User {
    
        private String firstName;
        private String surname;
    
        public User(Builder builder){
            firstName = builder.firstName;
            surname = builder.surname;
        }
    
        public String getFirstName(){
            return firstName;
        }
    
        public String getSurname(){
            return surname;
        }
    
        public static class Builder {
            private String firstName;
            private String surname;
    
            public Builder setFirstName(String firstName) {
                this.firstName = firstName;
                return this;
            }
    
            public Builder setSurname(String surname) {
                this.surname = surname;
                return this;
            }
    
            public User build(){
                return new User(this);
            }
    
        }
    
        public static void main(String[] args) {
            User.Builder builder = new User.Builder();
            User user = builder.setFirstName("John").setSurname("Doe").build();
        }
    
    }
    

提交回复
热议问题