Java Tutorial: “this” Keyword

, , …,

In Java there's “this” keyword. It can be used inside methods (and constructors).

The “this” keyword is used like a constant. It's value is the reference to the current object.

For example, if you have a class named CL, and it has method named “me”, then “this” in it would be a reference to a instance of the CL (that is: a CL object).

Example 1

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

public class Thiss {
    public static void main(String[] args) {
        CL cl = new CL();
        System.out.println( cl.x );
        System.out.println( cl.me().x ); // same as above
        System.out.println( cl.me().me().x ); // same as above
    }
}

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

Example 2

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.

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.

blog comments powered by Disqus