Java Reference
In-Depth Information
Generic Classes
Abstraction and polymorphism are at the heart of object-oriented programming. Defining a variable is an example
of abstraction where the variable hides the actual values. Defining a method hides the details of its implementation
logic, which is another form of abstraction. Defining parameters for a method is part of polymorphism that allows the
method to work on different types of value or objects.
Java 5 added a new feature called generics that allows for writing true polymorphic code in Java. Using generics,
you can write code without knowing the type of the objects you code operates on. It lets you create generic classes,
constructors, and methods.
A generic class is defined using formal type parameters. Formal type parameters are a list of comma-separated
variable names placed in angle-brackets (<>) after the class name in the class declaration. The following snippet of
code declares a class Wrapper that takes one formal type parameter:
public class Wrapper<T> {
// Code for the Wrapper class goes here
}
The parameter has been given a name T . What is T at this point? The answer is that you do not know. All you
know at this point is that T is a type variable, which could be any reference type in Java, such as String , Integer ,
Double , etc. The formal type parameter value is specified when the Wrapper class will be used. The classes that take
formal type parameter are also known as parameterized classes.
You can declare a variable of the Wrapper<T> class specifying the String type as the value for its formal type
parameter as shown below. Here, String is the actual type parameter.
Wrapper<String> stringWrapper;
Java lets you use a generic class without specifying the formal type parameters. This is allowed for backward
compatibility. You can also declare a variable of the Wrapper<T> class as shown:
Wrapper aRawWrapper;
When a generic class is used without specifying the actual type parameters, it is known as raw type. The above
declaration used the Wrapper<T> class as a raw type as it did not specify the value for T .
the actual type parameter for a generic class, if specified, must be a reference type, for example, String , Human ,
etc. primitive types are not allowed as the actual type parameters for a generic class.
Tip
A class may take more than one formal type parameter. The following snippet of code declares a Mapper class that
takes two formal parameters, T and R :
public class Mapper<T, R> {
// Code for the Mapper class goes here
}
You can declare variable of the Mapper<T, R> class as follows:
Mapper<String, Integer> mapper;
Here, the actual type parameters are String and Integer .
 
 
Search WWH ::




Custom Search