今天随便写写,大家都比较熟悉的基础知识(泛型),理论知识就不在这里细说了,请自行百度,直接上代码示例比较值观。
1. 泛型-类 使用
创建一个Entity实体类,如下:
package com;
public class SzlDemo {
private T uName;
private T uPwd;
private T uAge;
public SzlDemo() {
}
public SzlDemo(T uName, T uPwd, T uAge) {
this.uName = uName;
this.uPwd = uPwd;
this.uAge = uAge;
}
public T getuName() {
return uName;
}
public void setuName(T uName) {
this.uName = uName;
}
public T getuPwd() {
return uPwd;
}
public void setuPwd(T uPwd) {
this.uPwd = uPwd;
}
public T getuAge() {
return uAge;
}
public void setuAge(T uAge) {
this.uAge = uAge;
}
}
main函数测试
package com;
public class Test1 {
public static void main(String[] args) {
// 泛型类 使用
SzlDemo demo = new SzlDemo("sss", "bbb", "16");
System.out.println(demo.getuName() + " : " + demo.getuAge());
}
}
2. 泛型-接口 使用
创建接口定义
package com.api;
public interface SzlDemoApi {
T getMsg(T msg);
}
接口实现类
package com.api.impl;
import com.api.SzlDemoApi;
public class SzlDemoApiImpl implements SzlDemoApi {
@Override
public String getMsg(String msg) {
return "这是泛型案例,返回信息为:" + msg;
}
}
main函数测试
package com;
import com.api.SzlDemoApi;
import com.api.impl.SzlDemoApiImpl;
public class Test1 {
public static void main(String[] args) {
// 泛型接口 使用
SzlDemoApi szlDemoApi = new SzlDemoApiImpl();
String resutlMsg = szlDemoApi.getMsg("haha, 冲啊!!!");
System.out.println(resutlMsg);
}
}
3. 泛型-方法 使用
创建一个类,定义一个数字加法的方法
package com;
public class SzlDemo2 {
public static Double calPlus(T a, T b) {
return a.doubleValue() + b.doubleValue();
}
}
main函数测试
package com;
import com.api.SzlDemoApi;
import com.api.impl.SzlDemoApiImpl;
public class Test1 {
public static void main(String[] args) {
// 泛型方法 使用
int t1 = 3, t2 = 6;
System.out.println("Integer类型相加为:" + SzlDemo2.calPlus(t1, t2).intValue());
}
}