Java 使用构造函数内的派生类实例化基类引用
我有A1类和A2类,它们是从A类派生出来的。 我有一个对类的引用,我想使用它的构造函数根据参数通过A1或A2实例化对象Java 使用构造函数内的派生类实例化基类引用,java,polymorphism,Java,Polymorphism,我有A1类和A2类,它们是从A类派生出来的。 我有一个对类的引用,我想使用它的构造函数根据参数通过A1或A2实例化对象 class A { public A(bool someCondition) { if (someCondition) { //this = new A1() //this does not work } else { //this = new A2() //this does not wo
class A {
public A(bool someCondition) {
if (someCondition) {
//this = new A1() //this does not work
} else {
//this = new A2() //this does not work
}
}
}
有可能做到这一点吗 简单。只是不要在
构造函数中这样做。您需要一个静态生成器方法:
class A {
public static A build(bool someCondition) {
if (someCondition) {
return new A1();
} else {
return new A2();
}
}
}
然而,在构造函数A
中这样做是不可能的。任何特定类的构造函数都是这样的:给我这个特定类的实例,而不是其他;-) 为什么不用工厂呢