Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have an abstract method that accepts an argument of type "my type"?

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?

like image 241
Jack M Avatar asked Feb 03 '17 10:02

Jack M


People also ask

Can abstract method have arguments?

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.

Can you use abstract and final both with a method?

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”.


1 Answers

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>).

like image 171
Andy Turner Avatar answered Oct 21 '22 14:10

Andy Turner