Say, I have a simple class Fruit defined as follows:
public class Fruit {
int price;
public boolean isEqualPrice(Fruit object) {
return (object.price == price);
}
}
Now, there are several subclasses of Fruit such as Apple, Orange, Mango etc. I want the method isEqualPrice to be valid only when these subclasses are the same. For example, Apple.isEqualPrice(Apple) would be valid, but Apple.isEqualPrice(Orange) would not be. How should I define the parameter of isEqualPrice to acheive this? I don’t want to override isEqualPrice in every subclasses of Fruit.
One possible solution might be:
public boolean isEqualPrice(Fruit object) {
if(this.getClass() != object.getClass())
throw new IllegalArgumentException();
return (object.price == price);
}
But it will report classes are same or not only at runtime, and an user has no way to realize the correct parameter type watching the method signature. Is there any way to detect this at compile time?
NOTE: I think compareTo method of enum is such kind of method, as every enum has this method and a type of enum can’t be compared to other type. But I couldn’t understand how it is implemented.
Make Fruit generic, or add a generic subclass of fruit and derive Apple, Orange etc. from that.