我有一个类hirachy,如:Java的构造,使已经是正确的子类
class Main{
Main(Object input){ /* */}
}
class SubA extends Main{
SubA(Object input){
super(input);
// ...
}
}
class SubB extends Main{
SubB(Object input){
super(input);
// ...
}
}
什么我试图impement是,的Main
构造已经构造取决于在inputparameters一个子类。像这样:
// Non working example
class Main{
Main(Object input){
if (input.fullfillsSomeCond()) { return new SubA(input); }
if (input.fullfillsSomeOtherCond()) { return new SubB(input); }
}
}
这是非常不起作用的,因为我会因为递归而产生无限循环。有更好的建筑巫婆允许 Main somthing = new Main(myInput);
已经构建了正确的子类吗?
我认为,根据超类中指定的条件,不允许超类生成子类类型。也许看工厂模式 - 它是一个众所周知的模式,用于从一组可能性中创建特定的实现(包括子类):[工厂模式](https://en.wikipedia.org/wiki/Factory_method_pattern) –
无法在构造函数中返回任何内容。看看[工厂模式](https://www.tutorialspoint.com/design_pattern/factory_pattern.htm)。含义:不要使用构造函数,而要使用工厂的方法。 – f1sh
至少,你正试图从构造函数返回一个值!这在java中是不可能的 –