Why can’t this() and super() both be used together in a constructor?
What is the reason for incorporating such a thing?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
this(...)will call another constructor in the same class whereassuper()will call a super constructor. If there is nosuper()in a constructor the compiler will add one implicitly.Thus if both were allowed you could end up calling the
superconstructor twice.Example (don’t look for a sense in the parameters):
Now, if you call
new B(5)the following constructors are invoked:Update:
If you were able to use
this()andsuper()you could end up with something like this:(Attention: this is meant to show what could go wrong, if you were allowed to do that – which you fortunately aren’t)
As you can see, you’d run into a problem where the
A(boolean)constructor could be invoked with different parameters and you’d now have to somehow decide which should be used. Additionally the other constructors (A()andB()) could contain code that now might not get called correctly (i.e. out of order etc.) since the call tosuper( true )would circumvent them whilethis()wouldn’t.