zoukankan      html  css  js  c++  java
  • Java泛型小随笔

    今天随便写写,大家都比较熟悉的基础知识(泛型),理论知识就不在这里细说了,请自行百度,直接上代码示例比较值观。

    1. 泛型-类 使用

    创建一个Entity实体类,如下:

    package com;
    
    public class SzlDemo<T> {
    	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<String> demo = new SzlDemo<String>("sss", "bbb", "16");
    		System.out.println(demo.getuName() + " : " + demo.getuAge());
    	}
    }
    

    2. 泛型-接口 使用

    创建接口定义

    package com.api;
    
    public interface SzlDemoApi<T> {
    	T getMsg(T msg);
    }
    

     接口实现类

    package com.api.impl;
    
    import com.api.SzlDemoApi;
    
    public class SzlDemoApiImpl implements SzlDemoApi<String> {
    
    	@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<String> szlDemoApi = new SzlDemoApiImpl();
    		String resutlMsg = szlDemoApi.getMsg("haha, 冲啊!!!");
    		System.out.println(resutlMsg);
    	}
    }
    

    3. 泛型-方法 使用

    创建一个类,定义一个数字加法的方法

    package com;
    
    public class SzlDemo2 {
    
    	public static <T extends Number> 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());
    	}
    }
    
  • 相关阅读:
    方法转换IE、Firefox、Chrome区别
    splice方法便签
    webstorm主题网址+使用方法
    从程序员到项目经理(一):没有捷径
    界面原型图绘制工具Pencil
    程序员:伤不起的三十岁
    从程序员到项目经理(三):认识项目经理
    从程序员到项目经理(二):如何胜任
    原型制作软件 Axure RP
    软件界面原型设计工具 UIDesigner
  • 原文地址:https://www.cnblogs.com/jimmyshan-study/p/12767100.html
Copyright © 2011-2022 走看看