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 Constructor in parent class 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 "Constructor in parent class" Watch "Constructor in parent class" New topic
Author

Constructor in parent class

Shafeeq Sheikh
Ranch Hand

Joined: May 12, 2000
Posts: 68
Which statements concerning the following code are true?
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) {}
}
Select all valid answers:
A) The code will fail to compile.
B) The constructor in A that takes an int as argument will never be called as a result of constructing an object of class B or C.
C)class C has three constructors.
D)At most one of the constructors of each class is called as a result of constructing an object of class C
The answers given are B. and C. How is B true??? If one tries to instantiate class C with the 'int i' parameter, won't the constructor in Class A (with the int i parameter) get called too???
This is from JExam mock test....
Thanks.....
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Nope. Instanciating class C will call no arg constructor of each inheriting class. So ans is correct.
Edward Man
Ranch Hand

Joined: May 16, 2000
Posts: 40
Shafeeq,
1) Create an object of class B.
The default constructor for B is public B() {}. It is created by the java compiler for you. This default constructor also calls its super class's default constructor public A() {}.
2) Create an object of class C using the constructor public C(String msg) { this(); }.
This constructor call its own default constructor this(). It therefore creates an object of class B (See 1 above). B in turns calls the default constructor of A.
3) Create an object of class C using the constructor C(int) {}.
This constructor implicitly call B's default construcotr. It therefore creates an object of class B (See 1 above).
B also calls the default constructor of A.
4) You cannot call the private constructor C() { super(); } outside the class because it is private.
As you can see there is no such path that calls the constructor public A(int i) { this(); }. Therefore answer B is also correct.
Edward
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructor in parent class