S
SoulSpirit
Let's suppose we have an abstract class who wants to force its
subclasses to implement Comparable in a way that the extending class
has the ability to be compared only to objects of its same type.
The solution I can figure out is the following:
public abstract class Animal<T extends Animal> implements
Comparable<T>{
public abstract int compareTo( T other );
}
public class Dog extends Animal<Dog>{
public int compareTo( Dog other ){
return 0;
}
}
But it makes me doubtful about the necessity to declare the extending
class with a type parameter (Dog) that is the same as the class name.
I feel like I could eliminate the repetition (Dog-Dog) changing
something in Animal declaration, obtaining something like this:
public class Dog extends Animal{ //Notice, there isn't <Dog>
public int compareTo( Dog other ){
return 0;
}
}
Is it possible?
Thanks
subclasses to implement Comparable in a way that the extending class
has the ability to be compared only to objects of its same type.
The solution I can figure out is the following:
public abstract class Animal<T extends Animal> implements
Comparable<T>{
public abstract int compareTo( T other );
}
public class Dog extends Animal<Dog>{
public int compareTo( Dog other ){
return 0;
}
}
But it makes me doubtful about the necessity to declare the extending
class with a type parameter (Dog) that is the same as the class name.
I feel like I could eliminate the repetition (Dog-Dog) changing
something in Animal declaration, obtaining something like this:
public class Dog extends Animal{ //Notice, there isn't <Dog>
public int compareTo( Dog other ){
return 0;
}
}
Is it possible?
Thanks