aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Object Construction Flow Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Object Construction Flow" Watch "Object Construction Flow" New topic
Author

Object Construction Flow

M Sharma
Ranch Hand

Joined: Dec 13, 2001
Posts: 106
PROGRAM 1
----------


-----------------------------------------------
PROGRAM 2
-----------------------------------------------

Flow of program 1
----------------------
When the object of class b is constructed new B();
it calls the default constructor of class B which in-turn
calls superclass constructor but before the superclass constructor
executes it constructs an object of class C which calls default
constructor of class C printing "C"
The constructor call returns to constructor of class A and "B" gets printed and then call returns back to constructor of class B where again b"B" gets printed
So the output is CBB
Flow of program 2
----------------------
BUT IN CASE OF PROGRAM 2 the behaviour or i should say the flow seems to be bit different.
When the object of class Z is constructed...
First member varaible of class Z is initialized i.e... Y y = new Y();
So this leads to calling the constructor of class Y which in turn prints Y on the screen
Then the control return back to the constructor of class Z where an implicit call to the default constructor of superclass X gets called.
Now here the diffence is that in this case FIRST X IS PRINTED FROM THE CONSTRUCTOR OF CLASS X AND THEN THE CLASS MEMBER Y b = new Y(); gets executed
So in program 1 first the class member is initialized and then the constructor is executed but in case of program 2 first the constuctor is executed and then the class level member is initialized ...... why
Why is that difference in execution....... pls help !!!
[ September 23, 2003: Message edited by: Manish Sachdev ]

Regards, Manish
SCJP 1.4
Uma Balu
Ranch Hand

Joined: Aug 22, 2003
Posts: 61
Hi,

When the object of class Z is constructed...
First member varaible of class Z is initialized i.e... [b]Y y = new Y();

I think, it will first initialize the super class members, call super class constructor only then, initialize Z members and call its constructor.
Have a look at this,


Rgds,
Uma...
M Sharma
Ranch Hand

Joined: Dec 13, 2001
Posts: 106
Thanx a ton Uma. Your explaination made the flow very clear to me.
Thank you very much !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Object Construction Flow