I am working with an API in my company where I would like to create a subclass for an existing object. Here are the caveats:
- I cannot modify the superclass
- I cannot modify how the superclass object is instantiated
The example I see most commonly is a Dog as a subclass of Animal, so I will use that. Let's say you have this class in the API:
//API class, which I cannot modify
public class Animal(){
public void eat(){
//All animals can do this
}
}
Now I would like to create a class like this, which adds a few methods to Animal.
//My subclass, which I can modify
public class Dog extends Animal(){
public void fetch(){
//Only dogs can do this
}
}
So now let's say I have an instance of Animal (one that is not a Dog). I essentially need to downcast it into a Dog. I get that downcasting is not directly supported in Java, but is there any workaround for this?
public class AnimalExample{
public static void main(String[] args){
Animal animal = MyApi.getAnAnimal();
//Dog dog = (Dog) animal; ---throws a runtime error
Dog dog = Dog.getDog(animal); //Maybe something like this?
//Then I should be able to call both eat() and fetch()
dog.eat();
dog.fetch();
}
}
Again, I understand that downcasting is not directly supported. But there has to be some workaround for this, and I can't figure it out. I know that I could use a wrapper class (eg DogWrapper
), but that would be a little more difficult than I'd like because I still frequently call the dozens of superclass methods.
UPDATE: I understand that it's not yet a Dog, but I was wondering if there was a way to convert it into a Dog. It basically sounds like, from what people are saying, that I either have to convert it manually (copy each attribute/method over one-by-one) or just use a Wrapper class. A Wrapper class seems a lot less messy, so unfortunately I'll just have to go that route. So DogWrapper
will have a fetch()
method and a getAnimal()
method. So if I want the Dog
to eat, then I have to call dog.getAnimal().eat()
. I was avoiding having to do that, but I guess there's no way around it. Does anyone see anything simpler than that?