File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Which constructor is being called? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Which constructor is being called?" Watch "Which constructor is being called?" New topic
Author

Which constructor is being called?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
What will be printed when you execute the code?

A) Class A Constructor followed by Class B Constructor
B) Class B Constructor followed by Class A Constructor
C) Compile time error
D) Run time error
Answer : A)Class A Constructor followed by Class B Constructor
I feel the answer is B) because in the main , you are saying B b= new B(); hence Class B Constructor will be called first.
please explain.
Sonir
shiren shah
Greenhorn

Joined: Nov 16, 2001
Posts: 14
hi sonir,
sublcass constructor always by default implictly call super(), unless not declared explicitly.
Here
sublcass constructor will be excuted like this:
B() {super();
System.out.println("Class B Constructor"); }
so, Here first constructor exectued is B() but before it's s.o.p statment, A() constructor will be called and s.o.p of A() constructor will execute. Then program return back to execute s.o.p methode of B() constructor.
So,
Answer : A)Class A Constructor followed by Class B Constructor
Lubosh
Greenhorn

Joined: Jan 14, 2002
Posts: 1
I have a followup question on this issue. Say for example there is another class X, which is the super class of class A. (So it would be B extends A, and A extends X)
The order of execution for constructors in this situation would be: 1, constructor for class X, 2, constructor for class A and lastly 3, constructor for class B? Can anyone explain?
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Lubosh,
you are right, the first constructor to be invoked is the one of the "highest" superclass in the hierarchy because a class upon its creation must give the chance to all its superclasses to set their things up too...
We'd like you to read the Javaranch Naming Policy and register again.
Thank you for your cooperation.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Which constructor is being called?