• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor in parent class

 
Shafeeq Sheikh
Ranch Hand
Posts: 68
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
Nope. Instanciating class C will call no arg constructor of each inheriting class. So ans is correct.
 
Edward Man
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic