Two uses of "this" keyword are 1) To resolve the ambiguity between instance variables and parameters. 2) To pass the current object as a parameter to another method.
consider this code:
the code provides a class definition that demonstrates these uses.The MyDate class declares instance variables, (lines 2-4). One of the parameters to one of the constructors(line 6-10) is also called day,so in that context the keyword this resolves the ambiguity(line 7).The addDays method creates a new date object(line 18).IN THIS CONSTRUCTOR CALL,the method uses this keyword as an argument to refer to the current object. please note the line codes which has a * .I have numbered the code for you for more understanding. thank you Ammar Salem
[ January 17, 2008: Message edited by: Ammar Salem ] [ January 17, 2008: Message edited by: Ammar Salem ]
****************************<br />For Some Dreams.....<br />One Lifetime Is Not Enough.<br />****************************
If I make a new Rectangle(20, 20), it would first go into constructor 1 and then, with the this keyword go into the constructor 2. Is that right?
Thanks once more folks! [ January 18, 2008: Message edited by: Andre Brito ]
Joined: Dec 03, 2007
You defined 3 constructors here. 1. No parms 2. 2 parms 3. 3 Parms
So when you create an instance of the class by calling new Rectangle(), the constructor with no parm (1) gets invoked. When you use new Rectangle(20,20) the second contructor only gets called. No other constructors are invoked. Similarly with the 3 parm option, the third one will get called.
Now since you have this(0, 0, 0, 0); code in the costructor 1, a call new Rectangle() will eventually cause the cotrol to go to constructor 3. Similar is the case with constructor 2 . But note that only the new Rectangle() call goes to constructor 1. When you use new Rectangle(20,20), it control goes to constructor 2 but will never go to constructor 1.
So, both of my constructor (the first one and the second one) calls the constructor that has 4 arguments? (Because of keyword "this")?
Joined: Dec 03, 2007
Yes. Both of them calls the constructor with 4 arguments because you have a call like "this(x,y,z,q);". But note that once that call is executed, the control gets back to the original contructor and continue executing the statements there.
We think you got the concept here. Keep exploring..