一、泛型方法。
复制代码
1
2
3
4/* * 泛型方法:把泛型定义在方法上。格式:public <泛型类型> 返回类型 方法名(泛型类型 t) public <T> void show(T t){} */
定义ObjectTool类
复制代码
1
2
3
4
5
6package cn.itcast_05; public class ObjectTool { public <T> void show(T t) { System.out.println(t); } }
定义ObjectToolDemo类
复制代码
1
2
3
4
5
6
7
8
9public class ObjectToolDemo { public static void main(String[] args) { // 定义泛型方法后 ObjectTool ot = new ObjectTool(); ot.show("hello"); ot.show(100); ot.show(true); } }
二、泛型接口。
/*
* 泛型接口:把泛型定义在接口上
* 格式:public interface 接口名<泛型类型1…>
*/
首先定义一个泛型类:
复制代码
1
2
3public interface Inter<T> { public abstract void show(T t); }
接着分两种格式:
1、已知泛型是什么类型。
InnerDemo类:
复制代码
1
2
3
4
5
6
7public class InterDemo { public static void main(String[] args) { // 第一种情况的测试 Inter<String> i = new InterImpl(); i.show("hello"); } }
定义接口实现自Inter
复制代码
1
2
3
4
5
6public class InterImpl implements Inter<String> { @Override public void show(String t) { System.out.println(t); } }
2、不知道是什么类型。
InnerDemo类:
复制代码
1
2
3
4
5
6
7
8
9public 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
复制代码
1
2
3
4
5
6
7//第二种情况:还不知道是什么类型的,在创建对象的时候才给定 public class InterImpl<T> implements Inter<T> { @Override public void show(T t) { System.out.println(t); }//这种情况时,接口Inter写<T>实现子类名InterImpl也要定义成<T>的形式 }
转载于:https://www.cnblogs.com/wanghang/p/6299727.html
最后
以上就是沉静白羊最近收集整理的关于《java入门第一季》之泛型方法和泛型接口的全部内容,更多相关《java入门第一季》之泛型方法和泛型接口内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复