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?
Yes, we can provide parameters to abstract method but it is must to provide same type of parameters to the implemented methods we wrote in the derived classes.
But, in-case of abstract, you must override an abstract method to use it. Therefore, you cannot use abstract and final together before a method. If, you still try to declare an abstract method final a compile time error is generated saying “illegal combination of modifiers: abstract and final”.
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>
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With