泛型(java)

來源:互聯網
上載者:User

下面代碼是java泛型的例子

 

/**
 * 自訂屬性類型的類
 *
 * @author limeteor
 *
 */
public class Student<T> {
 String name;//名稱
 T address;//自訂類型 的地址
 
 /**
  * 地址的get()方法
  * @return 自訂類型
  */
 public T getAddress(){
  return address;
  
 }
 
 /**
  * 地址的set()方法
  * @param 自訂類型
  */
 public void setAddress(T address){
  this.address = address;
 }
 
 /**
  * 名稱的get()方法
  * @return String類型
  */
 public String getName(){
  return name;
  
 }
 /**
  * 名稱的set()方法
  * @param name
  */
 public void setName(String name){
  this.name = name;
 }
 
 /**
  * 無參數的構造方法
  */
 public Student(){
  super();
 }
 
 /**
  * 有二個參數的構造方法
  * @param name
  * @param address
  */
 public Student(String name,T address){
  super();
  this.name = name;
  this.address = address;
 }
 
 
 /**
  * main()方法
  * @param args
  */
 public static void main(String[] args) {
  Student<String> stu = new Student<String>();
  stu.name="Limeteor";
  stu.address = "中國陝西西安158號";
  System.out.println(stu.getAddress());
  
  Student<Address> stu1 = new Student<Address>();
  stu1.setName("qingqing");
  stu1.setAddress(new Address("中國", "陝西", "西安", 158));
  System.out.println(stu1.getAddress());
 }
}

/**
 * 定義一個類
 *
 * @author limeteor
 *
 */
class Address {
 String country;// 國家
 String city;// 城市
 String street;// 街道
 int no;// 門牌號

 /**
  * 帶參數的構造方法
  *
  * @param country
  * @param city
  * @param street
  * @param no
  */
 public Address(String country, String city, String street, int no) {
  super();
  this.country = country;
  this.city = city;
  this.street = street;
  this.no = no;
 }

 /**
  * 無參數的方法
  * @return 返回詳細的地址資訊
  */
 public String toString() {
  return country + city + street + no + "號";
 }
}

 

 

要注意的知識點有

1.定義一個泛型類,就是在類名後面的角括弧中定義一個名稱,代表一個資料類型,在本類中被用到。

2.T在程式中可以稱為一種特定的資料類型。

3.T在類中可以用作成員變數的類型,方法參數類型,方法傳回值類型。

4.在定義Student對象時,需要指明T的實際類型,這裡指定的是String類型,同樣指明的是Address類型。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.