Let's say someone gives you a class, Super
, with the following constructors:
public class Super
{
public Super();
public Super(int arg);
public Super(String arg);
public Super(int[] arg);
}
And let's say you want to create a subclass Derived
. How do you conditionally call a constructor in Super
?
In other words, what is the "proper" way to make something like this work?
public class Derived extends Super
{
public Derived(int arg)
{
if (some_condition_1)
super();
else if (some_condition_2)
super("Hi!");
else if (some_condition_3)
super(new int[] { 5 });
else
super(arg);
}
}
Constructor Calling form another Constructor The calling of the constructor can be done in two ways: By using this() keyword: It is used when we want to call the current class constructor within the same class. By using super() keyword: It is used when we want to call the superclass constructor from the base class.
No. It is not possible.
putting if/else statements inside of both the constructor and setters are valid often used. It ensures that the object is never in an invalid state.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
Use static factories, and four private constructors.
class Foo {
public static Foo makeFoo(arguments) {
if (whatever) {
return new Foo(args1);
} else if (something else) {
return new Foo(args2);
}
etc...
}
private Foo(constructor1) {
...
}
...
}
Yeah, what @Johan Sjöberg said.
Also looks like your example is highly contrived. There's no magical answer which would clear this mess :)
Usually, if you have such a bunch of constructors it would be a good idea to refactor them as four separate classes (a class should be only responsible for one type of thing).
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