File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Which constructor is being called?" Watch "Which constructor is being called?" New topic

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.
shiren shah

Joined: Nov 16, 2001
Posts: 14
hi sonir,
sublcass constructor always by default implictly call super(), unless not declared explicitly.
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.
Answer : A)Class A Constructor followed by Class B Constructor

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

Joined: Aug 26, 2001
Posts: 7610
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.

[Blog] [Blogroll] [My Reviews] My Linked In
I agree. Here's the link:
subject: Which constructor is being called?
It's not a secret anymore!