Consider the following example in Java. Where I have a method that takes an object of type Dog(which extends Animal), and need to pass it an object of type Animal. I can downcast explicitly but want to avoid this and keep type safety. Is there a way of going about this using type generics in Java? Thanks!
Edit To clarify what I'm doing: I am trying to refactor away duplicate code (I have the exact same code at the top level, but depending on what type of object is being passed will have very different behaviors in how calculations are done, and what data/methods is available etc.
Downcasting explicitly is a really simple way of doing it, but was trying to avoid that as it's frowned upon in general and I thought there might be a more proper solution using generics.
In short, at compile time, I will know which type of Animal I will have, as I create separate instances of my class for each type of animal. I thought there would be away to pass the type down as I create each instance, and have the compiler understand what type of object it is and do the casting safely for me.
public class Test {
interface Animal {
void speak();
}
class Cat implements Animal {
@Override
public void speak() {}
}
static class Dog implements Animal {
@Override
public void speak() {}
public void doDogThing() {}
}
static void dogMethod(Dog d) {
d.doDogThing();
}
public static void main(String[] args) {
Animal a = new Dog();
dogMethod(a);
}
}