【发布时间】:2010-03-11 13:19:27
【问题描述】:
美好的一天, 我有以下问题: 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。
提前致谢。
【问题讨论】:
-
我怀疑它在您的实际代码中没有显示在您在此处发布的伪代码中。伪代码看起来不错。
-
堆栈跟踪在代码中的哪个位置指示异常被抛出?
-
删除您的构建并重新编译所有类 - 仍然没有编译时错误?
-
@Thomas 完全重建工作!谢谢!
标签: java runtimeexception