Java Programming/Keywords/this

From Wikibooks, open books for an open world
Jump to: navigation, search

this is a Java keyword. It contains the current object reference.

  1. Solves ambiguity between instance variables and parameters .
  2. Used to pass current object as a parameter to another method .

Syntax:

this.method();
or
this.variable;

Example #1 for case 1:

Computer code
public class MyClass
 {
    //...
    private String value;
    //...
    public void setMemberVar( String value )
    {
        this.value= value;
    }
 }

Example #2 for case 1:

Computer code
public class MyClass
 {
    MyClass(int a, int b) {
        System.out.println("int a: " + a);
        System.out.println("int b: " + b);
    }
    MyClass(int a) {
        this(a, 0);
    }
    //...
    public static void main(String[] args) {
        new MyClass(1, 2);
        new MyClass(5);
    }
 }