This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
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


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors" Watch "Constructors" New topic
Author

Constructors

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. }
5.
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
Hello,
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,
super(6);
So the new form of Child constructor is:
Child(int j) {
super(j);
i=5;
}
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:
JVM:
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!
Regards,
Manfred.
Parimala Somasundaram
Ranch Hand

Joined: Mar 31, 2001
Posts: 41
Thanks Manfred, Jini.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Constructors