本文介绍了扩展超类和ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超类,我想重写两个方法.这是我的代码:

I have a superclass, which two methods i want to override. Here's my code:

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对象作为参数传递,接下来我要做什么:

I have some constructor, that passes SomeSuperClass object as a parameter, and what i do next:

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.

That seems to be right, but i'm getting java.lang.ClassCastException in SomeSuperClass while executing.

如果我创建SomeSuperClassObject,则会丢失重写的方法.

if i create SomeSuperClassObject, i lose my overriden methods.

使用强制转换,即使eclipse中没有错误,应用程序也会崩溃.换句话说,我如何用自己的方法重写SomeSuperClass,并仍然使SomeSuperClass对象与OtherConstructor一起使用?如果重要的话,此代码适用于android应用.

With casting, even if there's no errors in eclipse, application crashes.In other words, how i can override SomeSuperClass with my own methods, and still get SomeSuperClass object to use with OtherConstructor?If it is important, this code is for android app.

推荐答案

通常,您可以将子类的实例强制转换为其父类:

As a general rule, you can cast an instance of a subclass to its parent class:

MyCustomClass object = new MyCustomClass(params);
SomeSuperClass superClass = (SomeSuperClass) object;

但是,您不能将超类的实例转换为子类:

However, you cannot cast an instance of a superclass to a subclass:

SomeSuperClass object = new SomeSuperClass(params);
MyCustomClass customClass = (MyCustomClass) object; // throws ClassCastException

这是因为MyCustomClass对象也是SomeSuperClass对象,但并非所有SomeSuperClass对象都是MyCustomClass对象.

This is because a MyCustomClass object is also a SomeSuperClass object, but not all SomeSuperClass objects are MyCustomClass objects.

您也许可以使用某些设计模式来解决此问题. Java本身倾向于经常使用装饰器模式.

You may be able to work around this with certain design patterns. Java itself tends to use the Decorator pattern a lot.

这篇关于扩展超类和ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 20:55