call default constructor inside of parameterized constructor after conditional check
So i have a default constructor, and a parameterized constructor. My understanding is that to call a default constructor within another constructor you have to enter this(); on the first line. The issue is that I want to have a boolean check within the parameterized constructor that calls on the default if the boolean fails. How would I accomplish this?
Code:
class Something
{
...
Something()
{
default stuff
}
Something(double x)
{
if (cond())
use parameters
else
//this is where i want to call the default constructor, if the conditional fails
}
private boolean cond()
{
return false;
}
}
Re: call default constructor inside of parameterized constructor after conditional ch
Wouldn't it makes more sense to have the check outside of the constructor itself? For example:
Code:
Something sg;
if(cond())
sg = new Something(x);
else
sg = new Something();
Re: call default constructor inside of parameterized constructor after conditional ch
It does indeed. Thank You
Re: call default constructor inside of parameterized constructor after conditional ch
Would that have to be inside of the main method? As far as method overloading is concerned is there a way to revert to the default constructor?
What if inside of the parameterized constructor I had that if(cond()) statement, but skipped the following else statement. In other words if the boolean check fails and nothing is constructed, would it just use the default values?
Re: call default constructor inside of parameterized constructor after conditional ch
It would be in whatever method you want to utilize the object. As for your second question, I'm not sure.
Re: call default constructor inside of parameterized constructor after conditional ch
Move the code of your no-arg constructor to anoher method:
Code:
public Ctor() { initialize(); }
private void initialize() { ... }
Now your other constructor can do things like this:
Code:
publict Ctor(<parameters>) {
if (<condition>)
<do something>;
else
initialize();
}
As you can see, your other constructor effectively calls your no-arg constructor by calling the initialize() method.
kind regards,
Jos