Java: “this” Keyword

By Xah Lee. Date: . Last updated: .

In Java there's keyword named this. It can be used inside methods and Constructors .

The value of this is the reference to the current object.

class C3 {
    int x = 1;
    C3 me () {return this;}
}

public class T4 {
    public static void main(String[] args) {
        C3 c3 = new C3();
        System.out.println( c3.x );           // prints 1
        System.out.println( c3.me().x );      // same as above
        System.out.println( c3.me().me().x ); // same as above
    }
}

In the above example, the method “me” returns “this”. So, c3.me() is equivalent to the object c3 itself. Therefore, c3.x and c3.me().x and c3.me().me().x are all the same.

Example 2

One common use of this is to refer to current class's variable this.var_name or method this.method_name(…).

class OneNumber {
    int n;
    void setValue (int n) {this.n=n;};
}

public class Thatt {
    public static void main(String[] args) {
        OneNumber x = new OneNumber();
        x.setValue(3);
        System.out.println( x.n );
    }
}

In the above example, the method “setValue” tries to set class variable “n” to the value of the method's argument also named “n”. Because the name n is already used in the parameter name, so n=n is absurd. The workaround is to use the “this” keyword to refer to the object. So, this.n is the class variable n, and the second n in this.n=n is the method's argument.

Calling Constructor

Another common use of this is to call constructor.

class BB {
    int x;

    BB (int n) {this.x = n;}
    BB () {this(1);}

}

public class AA {
    public static void main(String[] args) {
        BB bb = new BB();
        System.out.println( bb.x );
    }
}

Example 3

Another practical example of using “this” is when you need to pass your current object to another method. Example:

class B {
    int n;
    void setMe (int m) {
        C h = new C();
        h.setValue(this, m);
    };
}

class C {
    void setValue (B obj, int h) {obj.n=h;};
}

public class A {
    public static void main(String[] args) {
        B x = new B();
        x.setMe(3);
        System.out.println( x.n );
    }
}

In the above example, B has a member variable n. It has a method setMe. This method calls another class method and passing itself as a object.

There is also a “super” keyword used to refer to the parent class. See “super” keyword .