class Animal {}
class Fish extends Animal {
void swim() {
// fish specific logic/side effect
}
}
class Bird extends Animal {
void fly() {
// bird specific logic/side effect
}
}
interface SideEffect < T extends Animal > {
void mutateSomething(T);
}
class FishSideEffect implements SideEffect < Fish > {
@Override
void mutateSomething(Fish fish) {
fish.swim() // swim has fish specific side effects
}
}
void someMethod(Animal animal) {
FishSideEffect fishSideEffect = new FishSideEffect();
fishSideEffect(animal); // <- this won't work.
}
When a method parameter is a superclass, what is the best way to execute subclass specific logic?
I'd like to avoid
instanceof
and/or casting to the specific subclass- adding anything to Animal/Bird/Fish
Any helpful terminology for me to research would help too, cheers.
question from:https://stackoverflow.com/questions/65944248/java-generics-how-to-do-this-without-instanceof-or-casting