Java generics, how do you force a superclass to extend to two parameters of a method of the same type?
Suppose I have a class hierarchy as follows:
class Vehicle; class Car extends Vehicle; class Plane extends Vehicle;
I have a function to compare two objects
public <T extends Vehicle> generateDiff(T original,T copy)
During compilation, the above method ensures that the two objects are vehicles, but it cannot ensure that the types of the two objects are the same
generateDiff(new Car(),new Car()); //OK generateDiff(new Plane(),new Plane()); //OK generateDiff(new Car(),new Plane()); //WRONG
Can I use generics at compile time?
P. S: at present, if the classes of two objects are different, I have implemented it, and an exception will be thrown But I'm not satisfied with it
Thank you in advance
Solution
Yes, you can!
The parameter of type T is inferred, but you can specify the type:
MyClass.<Car>generateDiff(new Car(),new Plane()); // generates a compile error
Xinxin 200 Xinxin 200 200 200 200:200 200: CE X - 200 200 200:200 200 200:20045 200 x-
generateDiff(new Car(),new Plane()); // type is inferred as Vehicle MyClass.<Vehicle>generateDiff(new Car(),new Plane());
The above code assumes that generatediff () is a static method New flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag new flag