If u see the code, it is very clear that 2 different constructors have been used. Test1 y = new Test1(); will assign 20 to i and Test1 z = new Test1(y); will assign 30 to i.
GetVar will simply return the value of i which is 20 in first case and 30 in second as y and z are two different objects.
Just wanted to know like what was ur approach to say that it was just 30 and not 20 and 30?
Joined: Aug 30, 2004
This was my interpretation of the code. When y was created "i" gets the value 20, no problem Then when z is created it passes the copy of the memory reference stored in y to the constructor, "a" is pointing to the same object as y. then this() calls the no arg constructor which makes the value of i to 20 and then value of i is again changed to 30 (code i = 30). All this time a,y and z are pointing to the same memory location. so when GetVar() method is called it will display 30. Can u tell me where did i go wrong ??
Thank you [ December 22, 2004: Message edited by: Jugal Hans ]
"All this time a,y and z are pointing to the same memory location."
Note that you used the new operator to construct z, and z is pointing to a different location in memory. Also note that although z is constructed with the constructor that takes a Test1 parameter, the argument itself is never used in the constructor.
(1) first, a call to this() means calling a constructor which takes no parameter, i.e. Test1() which assigns a value of 20 to i (2) very next statement being modification of same value i to 30 (note that you are still in constructor so same copy of i for object Z will be modified) (3) hence the results are System.out.println("Value of y:" + y.GetVar());//20 here System.out.println("Value of z:" + z.GetVar());//30 here(as explained)