java 16 -7 泛型方法和泛型接口(泛型类相似)
2024-09-15 22:00:43
写一个ObjectTool类
泛型方法:把泛型定义在方法上
格式 public <泛型类型> 返回类型 方法名(泛型类型)
这样的好处是:
这个泛型方法可以接收任意类型的数据
public class ObjectTool {
public <T> void show(T t) {
System.out.println(t);
}
}
再写一个测试类
public class ObjectToolDemo {
public static void main(String[] args) {
ObjectTool ot = new ObjectTool();
ot.show("hello");
ot.show(100);
ot.show(true);
}
}
先写一个泛型接口类
泛型接口:把泛型定义在接口上
public interface Inter<T> {
public abstract void show(T t);
}
实现类:
/*
实现类在实现接口的时候
第一种情况:已经知道该是什么类型的了
*/
//public class InterImpl implements Inter<String> {
//
// @Override
// public void show(String t) {
// System.out.println(t);
// }
// } //第二种情况:还不知道是什么类型的
public class InterImpl<T> implements Inter<T> { @Override
public void show(T t) {
System.out.println(t);
}
} /*
测试类
public class InterDemo {
public static void main(String[] args) {
// 第一种情况的测试
// Inter<String> i = new InterImpl();
// i.show("hello"); // // 第二种情况的测试
Inter<String> i = new InterImpl<String>();
i.show("hello"); Inter<Integer> ii = new InterImpl<Integer>();
ii.show(100);
}
}
最新文章
- windows 物理内存获取
- Oracle insert大量数据经验之谈(转)
- GDC2016 【全境封锁】的全局照明技术
- [DNX]解决dnu restore时找不到Newtonsoft.Json的问题
- 【数据结构】非常有用的hash表
- Jquery 使用JSOPN实例
- 基于最大最小距离的分类数目上限K确定的聚类方法
- 检测android机器是否有GPS模块
- wx_sample.php
- 转 Could not create the view: An unexpected exception was thrown.问题解决
- WPF 完美截图 <;一>;
- 利用可变参实现fprintf函数
- (细节)My SQL中主键为0和主键自排约束的关系
- Eclipse 模板
- POJ2947-Widget Factory
- CentOS_mini下make安装
- 20个有用的linux命令行技巧
- shell脚本之tr命令使用
- [笔记] Python入门---time模块
- 【转】WCF服务的创建和发布到IIS