Java Reference
In-Depth Information
You will be using your type parameter named T inside the class code in instance variable declarations,
constructors, the get() method, and the set() method. Right now, T means any type for you, which will be known
when you use this class. Listing 4-2 has the complete code for the Wrapper class.
Listing 4-2. Using a Type Parameter to Define a Generic Class
// Wrapper.java
package com.jdojo.generics;
public class Wrapper<T> {
private T ref;
public Wrapper(T ref) {
this.ref = ref;
}
public T get() {
return ref;
}
public void set(T a) {
this.ref = ref;
}
}
Are you still confused about using T in Listing 4-2? Here, T means any class type or interface type. It could be
String , Object , com.jdojo.generics.Person , etc. If you replace T with Object everywhere in this program and
remove <T> from the class name, it is the same code that you had for the ObjectWrapper class.
How do you use the Wrapper class? Since its class name is not just Wrapper , rather it is Wrapper<T> , you may specify
(but do not have to) the value for T . To store a String reference in the Wrapper object, you would create it as follows:
Wrapper<String> greetingWrapper = new Wrapper<String>("Hello");
How do you use the set() and get() methods of the Wrapper class? Since you have specified the type of the
parameter for the class Wrapper<T> to be String , the set() and get() method will work only with String types.
This is because you have used T as an argument type in the set() method and T as the return type in the get()
method declarations. Imagine replacing T in the class definition with String and you should have no problem in
understanding the following code:
greetingWrapper.set("Hi"); // OK to pass a String
String greeting = greetingWrapper.get(); // No need to cast
This time, you did not have to cast the return value of the get() method. The compiler knows that
greetingWrapper has been declared of type String and its get() method returns a String . Let's try to store an
Integer object in greetingWrapper .
// A compile-time error. You can use greetingWrapper only to store a String.
greetingWrapper.set(new Integer(101));
The statement will generate the following compile-time error:
error: incompatible types: Integer cannot be converted to String
greetingWrapper.set(new Integer(101));
 
Search WWH ::




Custom Search