Reputation: 1660
I have a class hirachy like:
class Main{
Main(Object input){ /* */}
}
class SubA extends Main{
SubA(Object input){
super(input);
// ...
}
}
class SubB extends Main{
SubB(Object input){
super(input);
// ...
}
}
What I'm trying to impement is, that the constructor of Main
already constructs a subclass depending in the inputparameters. Something like:
// Non working example
class Main{
Main(Object input){
if (input.fullfillsSomeCond()) { return new SubA(input); }
if (input.fullfillsSomeOtherCond()) { return new SubB(input); }
}
}
This is obvoiously not working, since I'll generate infinite loops due to recursion. Is there a better architecture witch allows that
Main somthing = new Main(myInput);
already constructs the correct subclass?
Upvotes: 0
Views: 58
Reputation: 16084
It is impossible to do this utilizing the Constructor, but you could use a Factory Method:
class Main{
Main(Object input){}
public static Main create( Object input ) {
if (input.fullfillsSomeCond()) { return new SubA(input); }
if (input.fullfillsSomeOtherCond()) { return new SubB(input); }
// You might want to handle the case where input does not
// meet any of the above criteria.
throw new IllegalArgumentException("input must be either A or B!");
}
}
Usage:
// Instead of new Main( input ):
Main oMain = Main.create(myInput);
Along with that you may want to make Main
abstract and its CTOR protected
.
Drawback here is that Main
has to "know" about its subclasses and the conditions. But that were the case, too if it could be done through ctor.
Upvotes: 3