Java Reference
In-Depth Information
It is customary, not a requirement, to give one-character names to the formal type parameters, for example,
T , R , U , V , etc. Typically, T stands for “Type,” R for “Return,” etc. One-character names make the code more readable.
However, nothing stops you from declaring a generic class as follows, which has four formal type parameters named
MyType , YourType , Hello , and WhoCares .
public class Fun<MyType, YourType, Hello, WhoCares> {
// Code for the Mapper class goes here
}
Java will compile the above code, but readers of your code will complain for sure!
The formal type parameters are available inside the class body to be used as types. Listing 6-35 declares a generic
class Wrapper<T> .
Listing 6-35. Declaring a Generic Class Wrapper<T>
// Wrapper.java
package com.jdojo.cls;
public class Wrapper<T> {
private T obj;
public Wrapper(T obj) {
this.obj = obj;
}
public T get() {
return obj;
}
public void set(T obj) {
this.obj = obj;
}
}
The Wrapper<T> class uses the formal type parameter to declare instance variable obj to declare a formal
parameter for its constructor and set() method, and as a return type for the get() method.
You can create an object of the generic type by specifying the actual type parameter for the constructor as follows:
Wrapper<String> w1 = new Wrapper<String>("Hello");
Most of the time, the compiler can infer the actual type parameter for the constructor. In those cases, you
can omit the actual type parameter. In the following assignment statement, the compiler will infer the actual type
parameter for the constructor as String :
Wrapper<String> w1 = new Wrapper<>("Hello");
Once you have declared a variable of the generic class, you can think of the formal type parameter as the
specified actual type parameter for all practical purposes. Now, you can think that, for w1 , the get() method of the
Wrapper<T> class returns a String .
String s1= w1.get();
 
Search WWH ::




Custom Search