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.
Yes, you can (kind of)!
The type
Tis being inferred from the arguments, but you can specify the type:Without the typing the method, the type
Tis inferred to be the narrowest class that satisfies the bounds as used, so for parametersCarandPlane, the narrowest type that will work isVehicle, so these two lines are equivalent: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.