泛型类概述

  • 把泛型定义在类上

    定义格式

  • public class 类名<泛型类型1,…>

    注意事项

  • 泛型类型必须是引用类型 ```java class GenericTool { private Q q;

    public Q getObj() { return q; }

    public void setObj(Q q) { this.q = q; }

}

  1. ```java
  2. public static void main(String[] args) {
  3. GenericTool<String> tool = new GenericTool<>();
  4. //tool.setObj(1);//编译错误
  5. tool.setObj("a");
  6. String obj = tool.getObj();
  7. System.out.println(obj);//a
  8. GenericTool<Student> tool2 = new GenericTool<>();
  9. tool2.setObj(new Student("axin",20));
  10. Student obj1 = tool2.getObj();
  11. System.out.println(obj1);//Person [name=axin, age=20]
  12. }