我需要一个对象 B,但是当我执行“B.Get By ID()”时我得到了一个对象 A
public class A
{
public A()
{
}
public static A GetSelf()
{
return new A();
}
public static A GetByID()
{
return GetSelf();
}
}
public class B extends A
{
public B()
{
super();
}
public static B GetSelf()
{
return new B();
}
}
B.GetByID(); //returns A, i need B
最佳答案
您只能通过还在 B
中创建一个 B GetByID()
方法来做到这一点。虽然这有点难看......
基本上,您的 B.GetByID()
调用将解析为 A.GetByID()
;编译后的代码中没有任何内容表明它最初是 B.GetByID()
,并且在 GetByID()
中调用 GetSelf()
将无论如何都被解析为 A.GetSelf()
。
基本上,静态方法不允许以您想要的方式进行多态性。我建议您创建一个 AFactory
和一个 BFactory
子类,并以正常方式使用方法覆盖,使用 instance 方法。
关于java - 我如何为子类使用相同的工厂方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6694886/