4) Generics
Last updated
Last updated
Intro
Generic Class
Generic Method
Generic Class inheritance
Generic Interface
Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.
As shown in the preceding code, the declaration of generic class Parcel includes the type parameter T. After adding the type information, it’s read as Parcel or Parcel of T. The generic class Parcel defines a private instance variable of type T, and get() and set() methods to retrieve and set its value. Methods get() and set() use the parameter type T as their method parameter and return type.
With the generic class Parcel, UseGenericParcel can use method set() to assign an object of type Book. But UseGenericParcel can’t cast the retrieved object to an unrelated class, say, Phone. If it tries to do so, the code won’t compile (as shown in figure).