• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

[Exercise] Prove that base class constructor is always called

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fellow java'ers,
TIJ has a question that reads:
Prove that the base-class constructor are
(a) always called, and
(b) called before derived-class constructors.
My idea for (a) follows. Your suggestions welcomed.
Assume that the base class is A and the derived class is B.
e.g. class B extends A{ ... }
I could make the constructor private in the base class.
That way I know for sure that the instantiation of class B may fail if it can't find a ctor in A.

/// B.java
class A{
private A() { System.out.print("A ctor"); }
}
public class B extends A{}
Compiling this gives me the error:

Is this formal enough ? Have I covered all the bases?
Anyone want to give (b) a try?
Thanks
Pho
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Pho,
I don't think your example answers any of the questions. Getting a compiler error rarely proves anything! The following code can be used to prove both a and b.

Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic