extending superclass and ClassCastException
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.
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
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.