Is there any way of enforcing the subclass type on a parameter at compilation time?
Something like this
but not for instances - for classes?
I have the classes:
public abstract class Animal {
public abstract void follow(Animal a); // <-- how to declare it?
}
but I would like a subclass to never use the Animal
base class, but rather only itself (the deriving class) as parameter:
public class Fish extends Animal {
@Override
public void follow(Fish f) { // error here, since it expects Animal
tagAlong(f);
}
private void tagAlong(Fish f) {
// do something
}
}
I want a Fish
to only use parameters of type Fish
, not Animal
, the same way another subclass Parrot
would use only a Parrot
parameter on the method follow()
.
I would strongly prefer to enforce this at compilation time, but if nothing else is possible runtime is a (less desirable) option.