I was trying to understand
why this() and super() cant be used together?
I have read many of the related discussions here on stackoverflow and got many things understood. But just one confusion I still have is.
calling this() inside a constructor implicitly calls super()
consider this code..
class Top
{
int z;
Top()
{
System.out.println("Top default constructor");
}
}
class A extends Top
{
int x;
A(int num)
{
x=num;
System.out.println("A parameterized constructor");
}
A()
{
this(5);
System.out.println("A default constructor");
}
public static void main(String arg[])
{
new A();
}
}
and OUTPUT is :
Top default constructor
A parametrized constructor
A default constructor
I was not expecting the first line in output "Top default constructor" as there is no super() call, implicit or explicit.
So there is, probably, something which I misunderstood. Please explain.
Is it true that calling this() inside a constructor implicitly calls super()?
Calling this()
in a constructor will call the zero-args constructor for that class. If the zero-args constructor for that class doesn't have an explicit call to super(...)
, then yes, there will be an implicit call to the zero-args super()
constructor. If the zero-args constructor in your class has an explicit call to some other super
signature, then of course that's done instead.
This is true for constructors in general. In your A
class, since your A(int)
constructor doesn't have any call to this()
or super()
, the implicit super()
is done.
I was not expecting the first line in output "Top default constructor" as there is no
super()
call,implicit or explicit.
Yes, there is — an implicit one. :-)
The fundamental rule is this: Some base class constructor must be run prior to code in the derived class running. That's why calls to this(...)
or super(...)
must be the first thing in a constructor. If a constructor doesn't have an explicit call to super(...)
, there's always an implicit call to super()
(with no args).
Calling this()
inside a constructor invokes another constructor of the same class. The other constructor would call the super()
constructor (implicitly or explicitly), which is why you can't call both this()
and super()
in the same constructor, as that would result in two super()
constructors being called.
Note that whenever I write this()
or super()
I don't necessarily mean calls to a parameter-less constructor (except for the implicit call to super()
which is always to the parameter-less constructor of the super class, as commented by Joeblade). Both calls can have parameters.
In your code sample, A()
constructor calls A(int)
constructor (that's what this(5)
does), which calls Top()
(parameter-less) constructor implicitly.
this(5)
calls A(int num)
which calls super()
implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With