一、泛型方法。
/*
* 泛型方法:把泛型定义在方法上。格式:public <泛型类型> 返回类型 方法名(泛型类型 t) public <T> void show(T t){}
*/定义ObjectTool类
package cn.itcast_05;
public class ObjectTool {
public <T> void show(T t) {
System.out.println(t);
}
}
定义ObjectToolDemo类
public class ObjectToolDemo {
public static void main(String[] args) {
// 定义泛型方法后
ObjectTool ot = new ObjectTool();
ot.show("hello");
ot.show(100);
ot.show(true);
}
}二、泛型接口。
/*
* 泛型接口:把泛型定义在接口上
* 格式:public interface 接口名<泛型类型1…>
*/
首先定义一个泛型类:
public interface Inter<T> {
public abstract void show(T t);
}接着分两种格式:
1、已知泛型是什么类型。
InnerDemo类:
public class InterDemo {
public static void main(String[] args) {
// 第一种情况的测试
Inter<String> i = new InterImpl();
i.show("hello");
}
}定义接口实现自Inter
public class InterImpl implements Inter<String> {
@Override
public void show(String t) {
System.out.println(t);
}
}2、不知道是什么类型。
InnerDemo类:
public class InterDemo {
public static void main(String[] args) {
// // 第二种情况的测试。注意这里创建实例写法和上边不一样
Inter<String> i = new InterImpl<String>();
i.show("hello");
Inter<Integer> ii = new InterImpl<Integer>();
ii.show(100);
}
}定义接口实现自Inter
//第二种情况:还不知道是什么类型的,在创建对象的时候才给定
public class InterImpl<T> implements Inter<T> {
@Override
public void show(T t) {
System.out.println(t);
}//这种情况时,接口Inter写<T>实现子类名InterImpl也要定义成<T>的形式
}