this()
and super()
are incompatible.
When instantiating a class, if you do not put anything special (neither this()
or super()
), the first thing your constructor does is call the constructor of the immediate superclass (which in turn calls the constructor of its immediate superclass , so until you reach Object()
). If not specified otherwise, the default constructor (without parameters) of the superclass is called.
If you want to specify the constructor of the superclass that is invoked, you make super([parámetros])
as the first instruction (as we said before, it is the first thing that is done when executing the constructor).
Another way of looking at it is that if you do not put anything, there is a% co_of% implicit.
When you put super();
as first instruction , what you do is invoke another constructor of the same class, and it will be that constructor that decides which superclass constructor to call (explicitly or implicitly).
If you do
Car(){
super();
this(20);
}
first call this()
(implicitly invoking Vehicle()
), and then invoke Object()
. And Car(int)
in turn invokes Car(int)
that also invokes Vehicle(int)
.
If you do
Car(){
this(20);
super();
}
first you call Object()
which in turn invokes Car(int)
, and then Vehicle(int)
.
To avoid this situation, just follow the rules.
-
If you make% explicit% co, it must be the first constructor instruction.
-
If you make a Vehicle()
, it must be the first constructor instruction.
Since you can only have a first instruction from the constructor, you can not combine both.
Summary, putting a label on each constructor (constructor super()
is this()
)
class Vehicle{
Vehicle(){ // A
this(10);
}
Vehicle(int x){ //B
}
}
class Car extends Vehicle{
Car(){ // C
super();
}
Car(String s) { // D
this(10);
}
Car(int i) { // E
}
}
-
Invoking C: C - > A - > B - > Z
-
Invoking D: D - > E - > A - > B - > Z
-
Invoking E: E - > A - > B - > Z
A useful exercise is to put a Object()
in each constructor to see the execution flow.