After declaring the type parameter <T>
, the compiler does not know T
what type it is. If we need to call some class methods, the compiler will report an error.
class Test<T>{
void fn(T t){
System.out.println(t.charAt(0 )); //假设我们指定T是String或String的子类,我们想调用其charAt方法,这时编译器会报错
}
}
At this time, we need to give T
a subclass of the previous <T extends String>
, which means T
yes String
or String
, then the compilation can pass
package com;
class Test<T extends String>{
void fn(T t){
System.out.println(t.charAt(0 ));
}
}
public class App2 {
public static void main(String[] args) {
Test<String> test = new Test();
test.fn("123");
}
}
Boundary declarations have two purposes:
1. A method to obtain a boundary type
2. Only the boundary type or its subclasses can be instantiated, which is equivalent to a restriction
Test<Integer> test = new Test(); //error
There is no lower bound,<T super String>
Reference:
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ107