Rafi Kamal
Rafi Kamal

Reputation: 4600

Java inheritence: Validating Subclass Type at Compile Time

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.

Upvotes: 1

Views: 130

Answers (2)

Vitaliy
Vitaliy

Reputation: 8206

You certainly can:

class Fruit <T extends Fruit>{
    int price;
    public boolean isEqualPrice(T object1) {
        return (object1.price == price);
    }
}

class Mango extends Fruit<Mango>{

}

Upvotes: 1

JohnB
JohnB

Reputation: 13713

Make Fruit generic, or add a generic subclass of fruit and derive Apple, Orange etc. from that.

class Fruit {
   ...
}

class FruitGeneric<T extends Fruit> extends Fruit {
    public boolean isEqualPrice (T otherFruit) {
        ...
    }
}

class Apple extends FruitGeneric<Apple> {
   ...
}

class Orange extends FruitGeneric<Orange> {
   ...
}

Upvotes: 2

Related Questions