Reputation: 12367
I know that the first statement inside a constructor must be super() (or this()) and if not specified explicitly the compiler will insert it for us. taking that into account please see the below piece of code:
class Building {
Building() { System.out.print("b "); }
Building(String name) {
}
}
public class House extends Building {
House() { System.out.print("h "); }
House(String name) {
this(); System.out.print("hn " + name);
}
public static void main(String[] args) { new House("x "); }
}
In the main method I'm calling the overloaded constructor of the House class that takes one String argument. As this() is already called, this means super() is called impicitly. But what happens to the Building(String name) constructor? Doesn't it have to be called too? I know that this code works and produces b h hn x
but doesn't the matching constructor of the super class need to be called?
Upvotes: 0
Views: 120
Reputation: 2640
Let's put number at each lines of your code, to make it easier to explain where the pointer is going to execute your code :
1 class Building {
2 Building() { System.out.print("b "); }
3 Building(String name) { }
4 }
5
6 public class House extends Building {
7
8 House() { System.out.print("h "); }
9 House(String name) { this(); System.out.print("hn " + name); }
10
11 public static void main(String[] args) { new House("x "); }
12 }
When you are calling new House("x ");
here is what happen :
/*11*/ new House("x ") -- --> "b h hn x"
| |
/*9*/ this(); System.out.print("hn " + name); /* House(name) */
| ^
v |
/*8*/ super(); System.out.print("h "); /* House() */
| ^
v |
/*2*/ super(); System.out.print("b "); /* Building() */
| ^
v |
super() --------> /* Object() */
/* The super of Object() does nothing. let's go down. */
and all these calls will print : "b h hn x" as expected :)
Everytime you are creating a constructor, if you don't explicitely call another constructor, implicitely, the super();
is called
(in your case, The constructor of Building
).
Upvotes: 1
Reputation: 97178
You need to call one, and exactly one, constructor of the base class. In your example, as you correctly say, the no-argument constructor of the Building class will get called. The single-argument constructor will not get called.
There is no requirement for matching the parameter names or types between the base class constructor and the derived class constructor.
Upvotes: 3