Java Generics, how to enforce two arguments of a method that extend a superclass to have a same type?
generics, java
Solution
Yes, you can (kind of)!
The type `T` is being inferred from the arguments, but you can specify the type:
MyClass.<Car>generateDiff(new Car(), new Plane()); // generates a compile error
Without the typing the method, the type `T` is inferred to be the narrowest class that satisfies the bounds as used, so for parameters `Car` and `Plane`, the narrowest type that will work is `Vehicle`, so these two lines are equivalent:
generateDiff(new Car(), new Plane()); // type is inferred as Vehicle
MyClass.<Vehicle>generateDiff(new Car(), new Plane());
The above code assumes the `generateDiff()` is a static method. If it's an instance method, you could type your class and have that type used in your method.
Problem
Suppose I have a class hierarchy as follow: ``` class Vehicle; class Car extends Vehicle; class Plane extends Vehicle; ``` I have a function which compares the two object ``` public <T extends Vehicle> generateDiff(T original, T copy) ``` At compile time, the method above guarantees the two objects is `Vehicle`, but it cannot make sure the types of the two object are the same. ``` generateDiff(new Car(), new Car()); //OK generateDiff(new Plane(), new Plane()); //OK generateDiff(new Car(), new Plane()); //WRONG ``` Can I achive this at compile time using Generics? P.s: currently, I've implemented it will throw exception if the `Class` of two objects are not the same. But I'm not satisfied with this. Thanks in advance.