Let's say I have an abstract class Animal with an abstract method
public abstract Animal mateWith(Animal mate);
the problem is, if I create subclasses Snake and Armadillo, a call like this would then be legal:
mySnake.mateWith(myArmadillo);
But I only want snakes to be able to mate with snakes. I need to be able to define something like this:
public abstract Animal_Of_My_Class mateWith(Animal_Of_My_Class mate);
Is this possible in Java?
Self-bounded generics to the rescue:
abstract class Animal<T extends Animal<T>> {
abstract T mateWith(T mate);
}
then:
class Animal_Of_My_Class extends Animal<Animal_Of_My_Class> {
Animal_Of_My_Class mateWith(Animal_Of_My_Class mate) { ... }
}
Note that you can't constrain T
to be the implementing class (as in, you can't require that Animal_Of_My_Class extends Animal<Animal_Of_My_Class>
rather than Animal_Of_My_Class extends Animal<Another_Animal_Of_My_Class>
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.