• 《java入门第一季》之泛型方法和泛型接口


    一、泛型方法。

    /*
     * 泛型方法:把泛型定义在方法上。格式: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>的形式
    
    	
    }







  • 相关阅读:
    composer使用git作为仓储
    monolog记录日志
    lumen laravel response对象返回数据
    lumen中间件 Middleware
    AcWing 901. 滑雪
    leetcode 34. 在排序数组中查找元素的第一个和最后一个位置
    acwing 902. 最短编辑距离
    ACWING 844. 走迷宫
    leetcode 5199. 交换字符串中的元素
    AcWing 836. 合并集合
  • 原文地址:https://www.cnblogs.com/wanghang/p/6299727.html
Copyright © 2020-2023  润新知