【发布时间】:2011-05-14 17:40:14
【问题描述】:
我有一个超类,我想重写这两个方法。这是我的代码:
public class MyCustomClass extends SomeSuperClass {
protected MyCustomClass(params) {
super(params);
}
@Override
public void method1() {
super.method1();
/* here goes my code */
}
@Override
public void method2() {
super.method2();
/* here goes my another code */
}
我有一些构造函数,将 SomeSuperClass 对象作为参数传递,接下来我要做什么:
MyCustomClass object;
/* now i have object of type SomeSuperClass,
but with my own method1() and method2() */
object = (MyCustomClass) MyCustomClass.item(blahblah);
/* eclipse suggests casting, because MyCustomClass.item()
constructor still returns SomeSuperClass object */
otherobject = OtherConstructor.object(object);
//OtherConstructor passes SomeSuperClass object
这似乎是对的,但我在执行时在 SomeSuperClass 中得到 java.lang.ClassCastException。
如果我创建 SomeSuperClassObject,我会丢失我的重写方法。
使用强制转换,即使 eclipse 中没有错误,应用程序也会崩溃。 换句话说,我如何用我自己的方法覆盖 SomeSuperClass,并且仍然让 SomeSuperClass 对象与 OtherConstructor 一起使用? 如果很重要,此代码适用于 android 应用程序。
【问题讨论】:
-
MyCustomClass.item的代码是什么? -
它没有被覆盖,所以它(确实是,根据 eclipse 代码助手)只是使用超类方法
-
学究式,
MyCustomClass.item()不是“构造函数”,OtherConstructor.object()也不是
标签: java casting overriding classcastexception superclass