This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes constructor question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "constructor question" Watch "constructor question" New topic

constructor question

Ranch Hand

Joined: Dec 16, 2005
Posts: 103
Hello guru's,

The answer for the following question is B and C, I couldn't understand the answer E.
Pls explain to me.

Thanks, Raghu/K

class A{
public A(){}
public A(int i) { this();}
class B extends A{
public boolean B(String msg){return false;}
class C extends B{
private C() { super() }
public C(String msg) {this();}
public C(int i){}
A. The code will fail to compile.
B. The constructor in A that takes an int as an argument will never be called as a result of constructing
an object of class B of C.
C. Class C define three constructors.
D. Objects of class B cannot be constructed.
E. At most one of the construcotrs of each class is called as a result of constucting an object of class.
marc weber

Joined: Aug 31, 2004
Posts: 11343

A class can have overloaded constructors, as illustrated here in classes A and C. A constructor can call another constructor of the same class using the keyword this along with the appropriate arguments. (Note: You don't want to call another constructor by name, because then you would be creating another object.)

In this example, the class A constructor taking an int argument calls the overloaded no-args constructor.

Similarly, the class C constructor taking a String argument calls the overloaded no-args constructor.

So option E ("at most one of the constructors of each class is called...") is false, because calling A(int i) results in A() also being called, and calling C(String msg) results in C() also being called.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Ranch Hand

Joined: Dec 16, 2005
Posts: 103
Awesome explanation...

Thanks, Raghu.K
Aum Tao
Ranch Hand

Joined: Feb 14, 2006
Posts: 210
Also, remember that this() and super() should be the first statement in your constructor. However, only one of them can occur in your constructor definition.

SCJP 1.4 85%
I agree. Here's the link:
subject: constructor question
It's not a secret anymore!