aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Constructor" Watch "Constructor" New topic
Author

Constructor

Jugal Hans
Greenhorn

Joined: Aug 30, 2004
Posts: 17


In the above code I was expecting 30 to be displayed on both the occasions.
But it displayed 20 and 30
How come ??
Can anyone please please explain what is happening here ???

Thanks in advance for the help !!
Sharada Prasad CS
Greenhorn

Joined: Jan 12, 2004
Posts: 8
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?
Jugal Hans
Greenhorn

Joined: Aug 30, 2004
Posts: 17
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 ]
Joe Borderi
Ranch Hand

Joined: Oct 23, 2004
Posts: 151
"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.
Mandar Patki
Greenhorn

Joined: Jun 27, 2002
Posts: 16
its simple,

(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)
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Constructor
 
Similar Threads
== operator
Passing Arguments
importing packages in a class
Wrong Output?
Constructors--THIS() call