Overcoming Typecasting with Generics in Return Types
In OOP programming, classes often maintain collections of related objects. For instance, an Animal class might keep track of a list of friends, which can be instances of various subclasses such as Dog and Duck.
Traditionally, retrieving specific friends from this list requires typecasting due to the heterogeneous nature of the collection. This results in code like:
Mouse jerry = new Mouse(); jerry.addFriend("spike", new Dog()); jerry.addFriend("quacker", new Duck()); ((Dog) jerry.callFriend("spike")).bark(); ((Duck) jerry.callFriend("quacker")).quack();
To avoid this cumbersome typecasting, consider using generics to make the return type of the callFriend method specific to the correct subclass. However, in this specific scenario, specifying the return type as a parameter like:
public <T extends Animal> T callFriend(String name, T unusedTypeObj) { return (T)friends.get(name); }
is not helpful since the unused type parameter provides no additional information at runtime.
Instead, a workaround involves passing the class of the desired type as an argument to callFriend:
public <T extends Animal> T callFriend(String name, Class<T> type) { return type.cast(friends.get(name)); }
With this implementation, the method call becomes:
jerry.callFriend("spike", Dog.class).bark(); jerry.callFriend("quacker", Duck.class).quack();
This solution eliminates runtime typecasting and ensures that the returned object can safely be cast to the desired subclass.
The above is the detailed content of How Can Generics Eliminate Typecasting When Retrieving Objects from Heterogeneous Collections?. For more information, please follow other related articles on the PHP Chinese website!