It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors 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 "Constructors" Watch "Constructors" New topic


Parimala Somasundaram
Ranch Hand

Joined: Mar 31, 2001
Posts: 41
What is the effect of compiling the following code and then executing the 'Child' application?
1. public class Papa {
2. int i;
3. Papa(int j) {i=j;}
4. }
6. class Child extends Papa {
7. Child() {i=5;}
8. public static void main(String[] args) {
9. new Child();
10. }
11. }
A. Compiler error at line 6.
B. Compiler error at line 7.
C. Compiler error at line 9.
D. The code compiles but throws exception when the application is executed.
E. The code compiles and executes with no problems.
The answer is B. I can understand this. Since 'Papa' has non-default constructor, it does not get a no-parameter constructor at compile time. So line 7 will not compile, as the compile tries to call its superclass default constructor.
My question is: Will it compile if line 7 was:
Child(int k) { // do something
Does the compiler try to call the superclass no-parameter constructor only if the Child class has a no-parameter constructor?
Jini Varghese
Ranch Hand

Joined: Dec 06, 2000
Posts: 58
I think it will not. Try the code to confirm. Just changing the constructor to
Child(int j) {i=5;} will not remove the compiler error. Since the base class constructor takes an arg. and the base class does not have no-arg constructor, You have to explicitly call that,
So the new form of Child constructor is:
Child(int j) {
The above is one way to remove the compiler error.
The other way is by giving the base class a non-arg constructor.
Please somebody tell if I am wrong.....
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Parimala,
An easy way to think of it is:
All class constructors will have a first line that contains a call to the method super().
Therefore, if you don't type it in then the compiler will place the following line as the new first line in ALL class constructors:
super(); // New first line provided by your friendly Java compiler!
Parimala Somasundaram
Ranch Hand

Joined: Mar 31, 2001
Posts: 41
Thanks Manfred, Jini.
I agree. Here's the link:
subject: Constructors
It's not a secret anymore!