This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Originally posted by amal shah: so passing the this reference as in line 1 is equivalent to constructing an object of the Main class. In short this when passed,internally creates object of the class..is this conclusion correct...
Not quite correct.
When you use "this", you are NOT creating a new object, it uses the object that is already created.
Actually, you're code will never run properly, as you'll get a StackOverflowError. What happens is the following: 1) You create an instance of Main manually. 2) The Main() constructor runs. 3) The Main() constructor creates another instance of Main on // line 2 4) Go to step 2.
Check out the below code The ouput for above code will be.
You will see that when we use "this" then we are refering to the current instance of the class. So while the display method changed the value of the local variable, updateInstanceVariable method updated the instance member of the current object. [ September 24, 2007: Message edited by: Vaibhav Aggarwal ]
Joined: May 05, 2006
You will see that when we use "this" then we are refering to the current instance of the class. So while the display method changed the value of the local variable, updateInstanceVariable method updated the instance member of the current object.
Your code above displays use of (this) when the local variable hides the instance member of the class....
But i am confused with the code that i pasted in my first post with respect to usage of (this) passed in as parameter....
I don't think so....it ran properly.....it is just a parameter passed..
When Rob is saying that your problem "will never run properly", he meant that you can't actually instantiate a Main object without an runtime exception. The reason your program doesn't generate a runtime exception, is because you never intantiate a Main object -- which means that you never tested any of the constructors that you are trying to figure out.