0

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

Chiseled
  • 2,280
  • 8
  • 33
  • 59
  • When you are calling newMethod() ,why cant you call it on a derived class? like new Child().newMethod()? – Kumar Abhinav Sep 25 '14 at 19:15
  • Whats stopping you from creating a child class straightaway in Test? Child c = new Child()? – Utsav Gupta Sep 25 '14 at 19:15
  • You should create an instance of Child in method foo(). Or it's for some reasons impossible? – Sergiy Medvynskyy Sep 25 '14 at 19:18
  • @KumarAbhinav please refer to the above example. I have to call the foo method of "Other" class which returns an object of "parent" class . The newMethod has the operation that I want to perform on the data members of p belonging to the parent class – Chiseled Sep 25 '14 at 19:24
  • i hope this clears up as to why I cannot create an instance of the child class directly. – Chiseled Sep 25 '14 at 19:26

1 Answers1

2

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.

Update

This could help you too, maybe a duplicate? : How to downcast a Java object?

Community
  • 1
  • 1
GPierre
  • 100
  • 11