美好的一天,我有以下问题:B 类扩展了 A 类,并且在实例化 B 类后,两者的方法都被另一个类中的另一个方法调用(示例如下):
public class A{
//fields
//constructors
//methods
}
public class B extends A{
//fields
//constructors
//methods
}
public class CALLER{
public A getA(enum E){
return Factory.getB(otherobject,E);
}
}
public class Factory{
public static B getB(object o,enum e){
//do something with enums and get B
b = new B();
//populate b
return b;
}
}
B 类不会覆盖 A 类的任何方法。不知何故,在编译时这不会出现任何错误,但在运行时类 CALLER 除外:java.lang.NoSuchMethodError: Factory.getB(object,enum) A
我的问题是:如果 B 扩展 A 为什么来自不同类的方法不能返回 A,即使它的 return 子句直接返回 B 对象?事实上改变:
public static B getB(object, enum);
和
public static A getB(object, enum);
解决了异常,但随后我得到了另一个异常(classCast),因为显然在代码的其他部分它正在等待 B 类型对象,而不是 A。
提前致谢。