Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you have a reference to a superclass, then if you want to execute a specific subclass's method you MUST cast to the subclass. The only time you don't is when the method is abstract in the superclass and implemented in the subclass. This is a fundamental aspect of the way inheritance works in Java.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...