Xah Lee, , …,
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).
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.
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 the value of its argument to the class variable 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. 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 to refer to the parent class. See “super” keyword.
blog comments powered by Disqus