extending superclass and ClassCastException

左心房为你撑大大i 提交于 2019-12-22 08:37:11

问题


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  */
}

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 

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

if i create SomeSuperClassObject, i lose my overriden methods.

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.


回答1:


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

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

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




回答2:


From what I see it seems that MyCustomClass.item(blahblah) call returns something different (maybe the parent) than MyCustomClass. Its the only part in te code, where you are casting object...




回答3:


If the item() method is declared in SomeSuperClass, I doubt that it is returning an instance of MyCustomClass. So your cast (MyCustomClass) MyCustomClass.item(blahblah) would be invalid.




回答4:


looks like problem solved. I tried

object = new MyCustomClass(blahblah);

and it worked. BTW, can somebody explain that?



来源:https://stackoverflow.com/questions/4260864/extending-superclass-and-classcastexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!