閱讀181 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Java泛型--泛型實例--標識接口的定義

一個人的信息:

·基本信息

·聯係方式

此時,肯定要設計一個接口,因為隻有實現了此接口的類才應該可以表示出人的信息。

interface Info{		// 隻有此接口的子類才是表示人的信息
}

interface Info{		// 隻有此接口的子類才是表示人的信息
}
class Contact implements Info{	// 表示聯係方式
	private String address ;	// 聯係地址
	private String telphone ;	// 聯係方式
	private String zipcode ;	// 郵政編碼
	public Contact(String address,String telphone,String zipcode){
		this.setAddress(address) ;
		this.setTelphone(telphone) ;
		this.setZipcode(zipcode) ;
	}
	public void setAddress(String address){
		this.address = address ;
	}
	public void setTelphone(String telphone){
		this.telphone = telphone ;
	}
	public void setZipcode(String zipcode){
		this.zipcode = zipcode ;
	}
	public String getAddress(){
		return this.address ;
	}
	public String getTelphone(){
		return this.telphone ;
	}
	public String getZipcode(){
		return this.zipcode ;
	}
	public String toString(){
		return "聯係方式:" + "\n" +
				"\t|- 聯係電話:" + this.telphone + "\n" + 
				"\t|- 聯係地址:" + this.address + "\n" + 
				"\t|- 郵政編碼:" + this.zipcode ;
	}
};
class Introduction implements Info{
	private String name ;		// 姓名
	private String sex ;		// 性別
	private int age ;			// 年齡
	public Introduction(String name,String sex,int age){
		this.setName(name) ;
		this.setSex(sex) ;
		this.setAge(age) ;
	}
	public void setName(String name){
		this.name = name ;
	}
	public void setSex(String sex){
		this.sex = sex ;
	}
	public void setAge(int age){
		this.age = age ;
	}
	public String getName(){
		return this.name ;
	}
	public String getSex(){
		return this.sex ;
	}
	public int getAge(){
		return this.age ;
	}
	public String toString(){
		return "基本信息:" + "\n" +
				"\t|- 姓名:" + this.name + "\n" + 
				"\t|- 性別:" + this.sex + "\n" + 
				"\t|- 年齡:" + this.age ;
	}
};
class Person<T extends Info>{
	private T info ;
	public Person(T info){		// 通過構造方法設置信息屬性內容
		this.setInfo(info);
	}
	public void setInfo(T info){
		this.info = info ;
	}
	public T getInfo(){
		return this.info ;
	}
	public String toString(){	// 覆寫Object類中的toString()方法
		return this.info.toString() ;
	}
};

聯係方式作為信息:

public class GenericsDemo32{
	public static void main(String args[]){
		Person<Contact> per = null ;		// 聲明Person對象
		per = new Person<Contact>(new Contact("北京市","01051283346","100088")) ;
		System.out.println(per) ;
	}
};

基本信息作為信息:

public class GenericsDemo33{
	public static void main(String args[]){
		Person<Introduction> per = null ;		// 聲明Person對象
		per = new Person<Introduction>(new Introduction("李興華","男",30)) ;
		System.out.println(per) ;
	}
};



最後更新:2017-04-03 14:53:45

  上一篇:go javah 無法訪問 com.heshen.HelloWorld Error: 未在命令行中指定任何類。請嚐試使用 -help
  下一篇:go JNI 學習筆記