BlogAD

2015年1月25日 星期日

泛型


[Java]Generics(泛型)

參考資料:http://blog.johnsonlu.org/category/program/java/

test1.java
1package mypackage;
2public class test1 {
3    private int num;
4    public void setVal(int num) {
5        this.num = num;
6    }
7
8    public int getVal() {
9        return this.num;
10    }
11}
test2.java
1package mypackage;
2public class test2 {
3    private String str;
4    public void setVal(String str) {
5        this.str = str;
6    }
7
8    public String getVal() {
9        return this.str;
10    }
11}
index.java
1import mypackage.test1;
2import mypackage.test2;
3public class index {
4    public static void main(String[] argv) {
5        test1 t1 = new test1();
6        test2 t2 = new test2();
7
8        t1.setVal(123);
9        System.out.println(t1.getVal());
10        t2.setVal("This is test");
11        System.out.println(t2.getVal());
12    }
13}

沒有留言:

張貼留言