art*_*emy 4 java overriding casting classcastexception superclass
我有一个超类,我想要覆盖两个方法.这是我的代码:
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 */
}
Run Code Online (Sandbox Code Playgroud)
我有一些构造函数,它将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
Run Code Online (Sandbox Code Playgroud)
这似乎是对的,但我在执行时在SomeSuperClass中得到了java.lang.ClassCastException.
如果我创建SomeSuperClassObject,我将丢失我的重写方法.
使用强制转换,即使eclipse中没有错误,应用程序也会崩溃.换句话说,我如何使用自己的方法覆盖SomeSuperClass,并仍然使用SomeSuperClass对象与OtherConstructor一起使用?如果它很重要,此代码适用于Android应用程序.
Pow*_*ord 16
作为一般规则,您可以将子类的实例强制转换为其父类:
MyCustomClass object = new MyCustomClass(params);
SomeSuperClass superClass = (SomeSuperClass) object;
Run Code Online (Sandbox Code Playgroud)
但是,您不能将超类的实例强制转换为子类:
SomeSuperClass object = new SomeSuperClass(params);
MyCustomClass customClass = (MyCustomClass) object; // throws ClassCastException
Run Code Online (Sandbox Code Playgroud)
这是因为MyCustomClass对象也是SomeSuperClass对象,但并非所有SomeSuperClass对象都是MyCustomClass对象.
您可以使用某些设计模式解决此问题.Java本身倾向于使用Decorator模式.