泛型类及特点
- 泛型的类型参数可以是泛型类
class Cls1<T>{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
}
public class Test {
public static void main(String[] args) {
Cls1<Cls1<Integer>> cls1 = new Cls1<Cls1<Integer>>(new Cls1(100));
System.out.println(cls1.getData().getData());
}
}
- 泛型类可以同时设置多个类型参数
class Cls1<T>{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
}
class Cls2<T, T2>{
T a;
T2 b;
public Cls2(T a, T2 b){
this.a = a;
this.b = b;
}
public T getData(){
return a;
}
public T2 getData2(){
return b;
}
}
public class Test {
public static void main(String[] args) {
Cls1<Integer> cls1 = new Cls1<Integer>(10);
System.out.println(cls1.getData());
Cls1<String> cls2 = new Cls1<String>("法外狂徒");
System.out.println(cls2.getData());
Cls2<Integer, String> cls3 = new Cls2<Integer, String>(100, "帅");
System.out.println(cls3.getData());
System.out.println(cls3.getData2());
Cls2<Integer, Integer> cls4 = new Cls2<Integer, Integer>(100, 20);
System.out.println(cls4.getData() + cls4.getData2());
}
}
3. 泛型类可以继承泛型类
abstract class Cls1<T>{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
abstract void printInfo();
}
class Cls2<T, T2> extends Cls1<T>{
T a;
T2 b;
public Cls2(T a, T2 b){
super(a);
this.b = b;
}
public T2 getData2(){
return b;
}
@Override
void printInfo() {
// TODO Auto-generated method stub
System.out.println("输出");
}
}
public class Test {
public static void main(String[] args) {
Cls2<Integer, String> cls2 = new Cls2<Integer, String>(10, "张三");
System.out.println(cls2.getData() + cls2.getData2());
cls2.printInfo();
}
}
4. 泛型类可以实现泛型接口
abstract class Cls1<T>{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
abstract void printInfo();
}
interface Cls3<T>{
abstract void printInfoCls3(T t);
}
class Cls2<T, T2> extends Cls1<T> implements Cls3<T>{
T a;
T2 b;
public Cls2(T a, T2 b){
super(a);
this.b = b;
}
public T2 getData2(){
return b;
}
@Override
void printInfo() {
// TODO Auto-generated method stub
System.out.println("输出");
}
public void printInfoCls3(T t) {
// TODO Auto-generated method stub
System.out.println(t);
}
}
public class Test {
public static void main(String[] args) {
Cls2<Integer, String> cls2 = new Cls2<Integer, String>(10, "张三");
System.out.println(cls2.getData() + cls2.getData2());
cls2.printInfo();
cls2.printInfoCls3(100);
}
}