Java: Keyword "this"

Source: https://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class


Disambiguation

public int readInputStream_Char(InputStream stream) {
        this.stream = stream;
        InputStreamReader reader = new InputStreamReader(this.stream);
        int character = 0;
        try {
            character = reader.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return character;
    }

Calling Overloaded Constructors

public class MyClass {
    public MyClass(String foo) {
        this(foo, null);
    }
    public MyClass(String foo, String bar) {
        ...
    }
}

 


Builder Pattern Example

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

}

Nested Classes

public class Outer {
  protected int a;

  public class Inner {
    protected int a;

    public int foo(){
      return Outer.this.a;
    }

    public Outer getOuter(){
      return Outer.this;
    }
  }
}