Java – this keyword

Using this to access a field

In case a field is shadowed by method or constructor parameter, the field can be accessed using this keyword.

public class Example {
  public int val;
  public Example(int val) {
    this.val = val;
  }
  public static void main(String[] args) {
    Example obj = new Example(10);
    System.out.println(obj.val);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   8904
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Using this to call another constructor of same class

public class Example {
  public int val;
  public Example() {
    this(100);
  }
  public Example(int val) {
    this.val = val;
  }
  public static void main(String[] args) {
    Example obj = new Example();
    System.out.println(obj.val);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   8916
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments