Java 5.0中的范型(Generics)
Posted on 2005-09-13 23:50 Justfly Shi 閱讀(1205) 評(píng)論(2) 編輯 收藏 所屬分類: Study Tiger范型有兩種,類范型和方法范型。他們可以用于一些類似于C++中的模板之類的作用。
這里主要有這么幾點(diǎn)要注意:
0、范型類之間的轉(zhuǎn)型
1、范型類的繼承
2、范型方法的override
3、關(guān)鍵字 super 和exends的使用。
package cn.justfly.study.tiger.generics;

import java.util.Collection;

/**
* Sample of defining generics type
*
* @author Justfly Shi
* created at 2005-8-25 22:03:09
*/
public class Defination<G_T, G_B> {
private G_T _t = null;

private G_B _b = null;

public G_B getB() {
return _b;
}

public void setB(G_B b) {
_b = b;
}
//Generics Method
<G_A> G_A abc(G_A a,Defination<G_T, ? extends G_B> f)//keyword extends
{
return a;
}

//class Generics Method
static <G_F,G_F2> void test(G_F[] a, Collection super G_F> b)// keyword super
{
for (G_F o : a) {
b.add(o);
}
}

public G_T getT() {
return _t;
}

public void setT(G_T t) {
_t = t;
}

public Defination(G_T t, G_B b) {
super();
_b = b;
_t = t;
}

/**
* @param args
*/
public static void main(String[] args) {
Defination<A, A> d = new Defination<A, A>(new AImp2(), new AImp1());
printDefination(d);

// about extends
Defination<A, A> right = new SubDefination<A, A>(new AImp2(), new AImp1());
printDefination(right);
// Type mismatch: cannot convert from SubDefination// Defination// Defination// AImp1());

// Type mismatch: cannot convert from Defination// Defination// Defination// AImp1());
}

private static void printDefination(Defination<A, A> defination) {
A t = defination.getT();
A b = defination.getB();
System.out.println(t.getValue());
System.out.println(b.getValue());
}
}

class SubDefination<G_T, G_J> extends Defination<G_T, G_J> {

public SubDefination(G_T t, G_J b) {
super(t, b);
}
@Override
<G_A> G_A abc(G_A a, Defination<G_T, ? extends G_J> f) {
return super.abc(a, f);
}
}

class A {
String getValue() {
return "class A";
}
}

class AImp1 extends A {
public String getValue() {
return "class AImp1";
}
}

class AImp2 extends A {
public String getValue() {
return "class AImp2";
}
}
最后再推薦一篇中文的范型學(xué)習(xí)資料
在Eclipse 3.1中體驗(yàn)J2SE 5.0的新特性 : 第三部分 :范型
這里主要有這么幾點(diǎn)要注意:
0、范型類之間的轉(zhuǎn)型
1、范型類的繼承
2、范型方法的override
3、關(guān)鍵字 super 和exends的使用。








































































































最后再推薦一篇中文的范型學(xué)習(xí)資料
在Eclipse 3.1中體驗(yàn)J2SE 5.0的新特性 : 第三部分 :范型