一、泛型类及特点
1.1泛型的类型参数可以是泛型类
class Cls1{
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<Integer>(10));
System.out.println(cls1.getData().getData());
}
}
/*
10
*/
1.2泛型类可以同时设置多个类型参数
class Cls4<T,T2>{
T a;
T2 b;
public Cls4(T a,T2 b){
this.a = a;
this.b = b;
}
public T getData3(){
return a;
}
public T2 getData4(){
return b;
}
}
public class Test {
public static void main(String[] args) {
Cls4<Integer,String> c4 = new Cls4<Integer,String>(100,"wei");
System.out.println(c4.getData3());
System.out.println(c4.getData4());
System.out.println(c4.getData3() + c4.getData4()); //+表示连接起来,并不是相加
Cls4<Integer,Integer> c5 = new Cls4<Integer,Integer>(100,10);
System.out.println(c5.getData3());
System.out.println(c5.getData4());
System.out.println(c5.getData3() + c5.getData4());
int n = 0;
n = c5.getData3() + c5.getData4(); //泛型在旧版本不可以相加,现在可以相加
System.out.println("n=" + n);
}
}
/*
100
wei
100wei
100
10
110
n=110
*/
1.3泛型类可以继承泛型类
abstract class Cls1{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
abstract void printInfo(); //抽象方法
}
class Cls2<T,T2> extends Cls1{ //继承Cls1
T2 b;
public Cls2(T a,T2 b){
super(a);
this.b = b;
}
public T2 getData2(){
return b;
}
@Override
//可以把这个注释掉,在类前面继续加abstract,不需要实现这个方法
void printInfo() {
// TODO Auto-generated method stub
System.out.println("输出");
}
}
public class Test {
public static void main(String[] args) {
Cls2<Integer,String> cls = new Cls2<Integer,String>(10,"xiao");
cls.printInfo();
System.out.println(cls.getData());
System.out.println(cls.getData2());
}
}
/*
输出
10
xiao
*/
1.4泛型类可以实现泛型接口
abstract class Cls1{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
abstract void printInfo(); //抽象方法
}
//接口
interface Cls3{
abstract void printInfoInCls3(T t);
}
class Cls2<T,T2,T3> extends Cls1 implements Cls3{ //继承Cls1,接口Cl3,添加一个T3
T2 b;
public Cls2(T a,T2 b){
super(a);
this.b = b;
}
public T2 getData2(){
return b;
}
@Override
//可以把这个注释掉,在类前面继续加abstract,不需要实现这个方法
void printInfo() {
// TODO Auto-generated method stub
System.out.println("输出");
}
//接口实现
public void printInfoInCls3(T3 t) {
// TODO Auto-generated method stub
System.out.println(t);
}
}
public class Test {
public static void main(String[] args) {
Cls2<Integer,String,String> cls = new Cls2<Integer,String,String>(10,"xiao");
cls.printInfo();
System.out.println(cls.getData());
System.out.println(cls.getData2());
cls.printInfoInCls3("小伟");
}
}
/*
输出
10
xiao
小伟
*/