I find myself in a tight spot. I am building some logic on top of an existing project given to me in a jar. Hence I don't have the ability to modify these classes.
I want to write additional methods to an existing class to make it feature rich . These methods would operate on few instance data and use some of the existing instance methods too.
But since the class cannot be modified directly I am writing these additional methods in its new derived class. Consider the following example
public class Parent
{
public void existing method()
{
}
}
public class Child extends Parent
{
public void newMethod()
{
}
}
public class Other
{
public Parent foo()
{
Parent pr = new Parent();
return pr;
}
}
public class Test
{
Other o = new Other();
Parent p = o.foo;
Child c = (Child) p;
c.newMethod();
}
When I run this code I am getting a ClassCastException
. I am aware i am downcasting. Is there a way I can cast an object of base class to an object of derived class ?
If yes what would be a legitimate scenario in which one can downcast ?
If not then how should the above case be tackled ? . Should i be changing the design
Appreciate your comments / suggestions !!!
What you are trying to do go against the concept of polymophism and heritage, you can only put a child object into a parent object, since they share the same base properties, but you cannot try to cast a parent into his child.
I would suggest to create a "cast" method in your Other class where you would take everything that matters in the child then create a parent object with that data and return it.
Something like this :
public Parent downcast(Child c)
{
Parent cast = new Parent();
//Transfer data from the child to the parent
cast.setProperty(c.getProperty());
return cast;
}
There is probably a better solution than this, but it could solve your problem easily.
This could help you too, maybe a duplicate? : How to downcast a Java object?