Xah Lee, 2005-02
In java there's “this” keyword, that can be used inside methods (and constructers).
It returns the reference to the current object.
That is, if you have a class CL, and it has method “me”, then “this” in it would be a reference to a instance of the class (that is: a CL object).
Example:
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, since the method “me” returns “this”, which is the object itself. 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.
Another example:
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 setValue tries to set the value of the argument to the class variable n. Since 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. Thus we have “this.n=n”.
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 for refer to the parent class. See “super” keyword.
See also:
Page created: 2005-02. © 2005 by Xah Lee.