How can I use an abstract method that takes an argument of type "my type"?

Say I have an abstract Animal class with an abstract method

public abstract Animal mateWith(Animal mate); 

the problem is that if I subclass Snake and Armadillo, then such a call would be legal:

 mySnake.mateWith(myArmadillo); 

But I want the snakes to mate with the snakes. I need to define something like this:

 public abstract Animal_Of_My_Class mateWith(Animal_Of_My_Class mate); 

Is this possible in Java?

+6
source share
1 answer

Self-Closed Generics for Salvation:

 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 cannot restrain T as an implementing class (as in, you cannot require Animal_Of_My_Class extends Animal<Animal_Of_My_Class> , not Animal_Of_My_Class extends Animal<Another_Animal_Of_My_Class> ).

+7
source

Source: https://habr.com/ru/post/1014675/


All Articles