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