extending superclass and ClassCastException

喜欢而已 提交于 2019-12-05 12:25:28

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.

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...

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.

looks like problem solved. I tried

object = new MyCustomClass(blahblah);

and it worked. BTW, can somebody explain that?

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