Java泛型嵌套示例

时间:2023-02-05 20:50:01
/* 
* 泛型嵌套实例
* date: 2012-10-22
* author: Alex Hohh
*/

// 泛型类Info<K,V>
class Info<K,V>{
	private K key;
	private V value;
	
	// 构造函数
	public Info(K key, V val){
		this.key = key;
		this.value = val;	
	}	
	
	// 设置key
	public void setKey(K k){
		this.key = k;	
	}
	
	// 设置value
	public void setValue(V v){
		this.value = v;	
	}
	
	// 获取KEY
	public K getKey(){
	  return this.key;	
	}
	
	// 获取value
	public V getValue(){
		return this.value;		
	}
	
	// 覆写toString()方法
	public String toString(){
		return "Key: " + this.key + ", Value : " + this.value;
	}
}

// Demo<S>中的S在这代表Info<K,V>,实现泛型嵌套
class Demo<S>{
	
	// 泛型S的对象
	private S info;
	
	// Demo构造函数
	public Demo(S info)	{
		this.info = info;	
	}
	
	// 设置S类型的info
	public void setInfo(S info){
		this.info = info;	
	}
	
	// 获取info
	public S getInfo(){
		return this.info;	
	}
}

// main
public class GenericEmbeded{
	public static void main(String args[]){
		
		// 实例化Info类对象
		Info<String,Integer> info = new Info<String, Integer>("Alex Hohh",21);
		// 实例化Demo类对象,泛型嵌套
		Demo< Info<String,Integer> > d = new Demo< Info<String,Integer> >( info );

		// 获取Info<K,V>对象后,再调用toString()方法,最后输出.
		System.out.print( d.getInfo() );					
	}	
}

输出结果:

Java泛型嵌套示例