Posted on 2005-09-13 23:50
Justfly Shi 阅读(1198)
评论(2) 编辑 收藏 所属分类:
Study Tiger
范型有两种,类范型和方法范型。他们可以用于一些类似于C++中的模板之类的作用。
这里主要有这么几点要注意:
0、范型类之间的转型
1、范型类的继承
2、范型方法的override
3、关键字 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";
}
}
最后再推荐一篇中文的范型学习资料
在Eclipse 3.1中体验J2SE 5.0的新特性 : 第三部分 :范型