Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't this() and super() both be used together in a constructor?

Why can't this() and super() both be used together in a constructor?

What is the reason for incorporating such a thing?

like image 409
Babloo Avatar asked Apr 30 '12 09:04

Babloo


People also ask

Can you use both this () and super () in the same constructor?

this(...) will call another constructor in the same class whereas super() will call a super constructor. If there is no super() in a constructor the compiler will add one implicitly. Thus if both were allowed you could end up calling the super constructor twice.

Can we use this () and super () in a constructor in Java?

Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that's why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class's No arg constructor.

Can we use super and this together?

Constructor must always be the first statement. So we can not have two statements as first statement, hence either we can call super() or we can call this() from the constructor, but not both.


1 Answers

this(...) will call another constructor in the same class whereas super() will call a super constructor. If there is no super() in a constructor the compiler will add one implicitly.

Thus if both were allowed you could end up calling the super constructor twice.

Example (don't look for a sense in the parameters):

class A {   public A() {     this( false );   }    public A(boolean someFlag) {   } }  class B extends A {   public B() {     super();   }    public B( boolean someFlag ) {     super( someFlag );   }    public B ( int someNumber ) {     this(); //   } }  

Now, if you call new B(5) the following constructors are invoked:

     this( false); A() ---------------> A(false) ^ | | super();  | |     this(); B() <--------------- B(5)  <--- you start here 

Update:

If you were able to use this() and super() 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)

     this( false); A() ---------------> A(false) ^                    ^ |                    | | super();           | super( true ); <--- Problem: should the parameter be true or false?  |                    | |     this();        | B() <--------------- B(5)  <--- you start here 

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() and B()) could contain code that now might not get called correctly (i.e. out of order etc.) since the call to super( true ) would circumvent them while this() wouldn't.

like image 81
Thomas Avatar answered Oct 17 '22 07:10

Thomas