Generic Types
This lesson explains generic types in Java.
We'll cover the following...
Question # 1
Explain generic types?
To understand generic types, we can draw an analogy from methods. A method can be defined to receive input parameters. Each method invocation is passed different values for the input parameters and the method executes the same code everytime with different values. We take the same concept and extend it to types (classes and interfaces). We say that a class or an interface is now parameterized over types and is considered generic. The type parameter is the variable that can take on different values and the generic class runs the same code with the value of the type parameter substituted. Consider the class below:
Non generic class
class Printer {
void print(Integer k) {
System.out.println("printing : " + k.toString());
}
}
Say we wanted to write a Printer
class that can print an object in a customized way. The above class only caters to integers in its current form. We can make it generic so that it can be used for integers, strings, doubles and any other object. The generic form of the class appears as follows:
class Printer<T> {
void print(T t) {
System.out.println("printing : " + t.toString());
}
}
The type parameter is T
and now we can use the class for all reference types with Object
as a supertype. Note, generics classes or interfaces can't be parameterized over primitive types.
class Demonstration {public static void main( String args[] ) {(new Printer<Integer>()).print(Integer.valueOf(555));(new Printer<String>()).print("print away");(new Printer<Object>()).print(new Demonstration());}}class Printer<T> {void print(T t) {System.out.println("printing : " + t.toString());}}
Question # 2
What are generic methods?
Generic methods are methods that introduce their own type parameters (T, U, V, etc). This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Examples are given below:
Non generic class with generic method
class SimpleClass {
<T> void genericMethod(T t) {
System.out.println(t);
}
}
Note the above class itself isn't generic but it defines a generic method which can be invoked as follows:
SimpleClass sc = new SimpleClass();
sc.<Integer>genericMethod(Integer.valueOf(10));
We can also have a generic class define a generic method:
Generic class with generic method
class SimpleClass<T> {
<T> void genericMethod(T t) {
System.out.println(t);
}
}
Note that both the class and the ...