Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Help with "down casting"

843789Jul 4 2009 — edited Jul 29 2009
I know that the "down cast" below is not allowed but I've included the code to show what I want to achieve.
public class animal { ... }

public class cat extends animal { ... }

public class dog extends animal { ... }

animal myAnimal = new animal( );
// ... do some work on myAnimal

// now make myAnimal into a more specific cat.
cat myCat = (cat)myAnimal;
I know I could do this:
animal myAnimal = new cat( );

// ...

cat myCat = (cat)myAnimal;
But what if during the intervening "..." stage I change my mind and want myAnimal to be a dog instead.

I had thought of creating helper methods that could do a down cast "conversion":
animal myAnimal = new animal( );
// ... do work on animal

cat myCat = convertToCat( myAnimal );
// or
dog myDog = convertToDog( myAnimal );
but somehow this seems rather clumsy as inheritance already suggests a link between animal and cat (or dog).

So my question is: what is the best way I can achieve what is implied from the first code snippet?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 26 2009
Added on Jul 4 2009
37 comments
256 views