- public class fanxing
- {
- public static void main(String[] args)
- {
- new Person2(24).<String>print("zhangsan");//相比之下,书写上比较繁琐
- new Worker<String>("lisi",23).show();
- }
- }
- class Worker<T>//类级别泛型,整个类有效
- {
- private T obj;
- private int age;
- Worker(T obj,int age)
- {
- this.obj = obj;
- this.age = age;
- }
- public void show()
- {
- System.out.println(obj);
- System.out.println(age);
- }
- }
- class Person2
- {
- /*
- private Object obj;
- Person2(Object obj)
- {
- this.obj = obj;
- }
- */
- private int age;
- Person2(int age)
- {
- this.age = age;
- }
- public <T> void print(T obj)//方法级别泛型,这么写的确没错
- {
- //this.obj = obj;
- System.out.println(obj);
- System.out.println(age);
- }
- }
复制代码 |