Inheritance Rules for Generic Types Core Java

When you work with generic classes, you need to learn a few rules about inheritance and subtypes. Let’s start with a situation that many programmers find unintuitive. Consider a class and a subclass, such as Employee and Manager. Is Pair<Manager> a subclass of Pair<Employee>? Perhaps surprisingly, the answer is “no.” For example, the following code will not compile:

The minmax method returns a Pair<Manager>, not a Pair<Employee>, and it is illegal to assign one to the other.

In general, there is no relationship between Pair<S> and Pair<T>, no matter how S and T arerelated .

No inheritance relationship between pair classes

No inheritance relationship between pair classes

This seems like a cruel restriction, but it is necessary for type safety. Suppose we wereallowed to convert a Pair<Manager> to a Pair<Employee>. Consider this code:

Clearly, the last statement is legal. But employeeBuddies and managerBuddies refer to the same object. We now managed to pair up the CFO with a lowly employee, which should notbe possible for a Pair<Manager>.

NOTE: You just saw an important difference between generic types and Java arrays. You can assign a Manager[] array to a variable of type Employee[]:

However, arrays come with special protection. If you try to store a lowly employee into employeeBuddies[0], the virtual machine throws an ArrayStoreException. You can always convert a parameterized type to a raw type. For example, Pair<Employee>is a subtype of the raw type Pair. This conversion is necessary for interfacing with legacy code. Can you convert to the raw type and then cause a type error? Unfortunately, you can. Consider this example:

This sounds scary. However, keep in mind that you are no worse off than you were with older versions of Java. The security of the virtual machine is not at stake. When the foreign object is retrieved with getFirst and assigned to a Manager variable, a ClassCastExceptionis thrown, just as in the good old days. You merely lose the added safety that generic programming normally provides. Finally, generic classes can extend or implement other generic classes. In this regard, they are no different from ordinary classes. For example, the class ArrayList<T> implements the interface List<T>. That means, an ArrayList<Manager> can be converted to a List<Manager>. However, as you just saw, an ArrayList<Manager> is not an ArrayList<Employee> or List<Employee>.

Subtype relationships among generic list types

Subtype relationships among generic list types


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics