2011年12月31日星期六

第10天第7节: 泛型操作

==Usage on Class
package generic.test;
public class Point<T extends Number> {
    private T x;
    private T y;
    public Point(T x, T y) {
        super();
        this.x = x;
        this.y = y;
    }
    public String getInfo() {
        return "x= " + x + ", y = " + y;
    }
}

package generic.test;
public class TestPoint {
    public static void main(String[] args) {
        Point<Integer> p1 = new Point<Integer>(10, 20);
        Point<Float> p2 = new Point<Float>(20.0f, 30.0f);
        print(p1);
        print(p2);
    }
    public static void print(Point<?> p){
        System.out.println(p.getInfo());
    }
}
----java output----
x= 10, y = 20
x= 20.0, y = 30.0

Note: extends defines the upper limits, supper defines the lower limits

==Usage on Interface
package generic.test;
public interface draw<T> {
    void start(T p);
    void end(T p);
}
class Point<T> implements draw<T> {
    public void start (T p) {
        System.out.println("point start" + p);
    }
    public void end (T p) {
        System.out.println("point end" + p);
    }
}
class Line implements draw<Line> {
    public void start(Line p) {
        System.out.println("line start" + p);
    }
    public void end(Line p) {
        System.out.println("line ends" + p);
    }
}
package generic.test;
public class TInterface {

    public static void main(String[] args) {
        Point<Integer> p = new Point<Integer>();
        Line l = new Line();
        p.start(0);
        p.end(10);
        l.start(l);
        l.end(l);
    }
}
----java output----
point start0
point end10
line startgeneric.test.Line@e2cb55
line endsgeneric.test.Line@e2cb55


==Usage on Method
public class Tmethod {
    public static void main(String[] args) {
        for(int i:teven(1,2,3)) {
            System.out.println(i);
        }
    }
    public static <T> T[] teven(T... tn) {
        return tn;
    }

}

----java output----
1
2
3


==Recursive Usage
package generic.test;
class Info<T> {
    private T param;
    public T getParam() {
        return param;
    }
    public void setParam(T param) {
        this.param = param;
    }
}

class Person<T> {
    private T info;
    public T getInfo() {
        return info;
    }
    public void setInfo(T info) {
        this.info = info;
    }
}

public class Trecursive {
    public static void main(String[] args) {
        Person<Info<String>> per = new Person<Info<String>>();
        per.setInfo(new Info<String>());
        per.getInfo().setParam("mldnjava");
        System.out.println(per.getInfo().getParam());
    }

}


----javaoutput----
mldnjava

没有评论: