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.
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?
来源:https://stackoverflow.com/questions/4260864/extending-superclass-and-classcastexception