Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a constructor with a condition [duplicate]

I would like to do something like this:

if (condition)
    super(foo.class);
else
    super(bar.class);

But the super constructor has to be the first in the constructor. Is it possible to do this anyway?

like image 957
Eko Avatar asked May 02 '14 08:05

Eko


People also ask

Can I call a constructor twice?

you cannot call the constructor more than once for a one object but you can call it recursively.

In which condition copy constructor is called?

In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value. 2) When an object of the class is passed (to a function) by value as an argument. 3) When an object is constructed based on another object of the same class.

Can we have if condition in constructor?

Yes. Just make sure that the new Object is has all its variables in a decent state regardless of which conditional paths are executed.

Is it possible to call a constructor from another within the same class not from a subclass )? If yes how?

Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.


1 Answers

Assuming you're calling the same superconstructor in both cases and just passing in a different argument, you can just use the conditional operator:

super(condition ? Foo.class : Bar.class);
like image 82
Jon Skeet Avatar answered Sep 24 '22 00:09

Jon Skeet