Java泛型初探

在做安卓项目中看到别人写的基类里各种用到泛型,能够看懂并使用。感觉对于Java学习还是很重要的一块,在以后的code生涯中会遇到很多,所以刷个博客作为学习笔记。

泛型(Template)比如你在写基类或者API之类的时候,由于Java是强类型语言,所以无法预料到将来继承你写的基类的人会用什么类型的数据,比如String、Integer或者是他自己定义的类。因此,泛型横空出世(这里全是我自己的见解,到底为什么出现泛型我也没有去查)。接下来举个实例,应该就比较好了解泛型的作用和使用了。

 1 class Template<T> {
 2     public T getOb() {
 3         return ob;
 4     }
 5 
 6     public void setOb(T ob) {
 7         this.ob = ob;
 8     }
 9 
10     private T ob;
11 
12     public Template(T ob) {
13         this.ob = ob;
14     }
15     public void showOb() {
16         System.out.println("ob的类型是:" + ob.getClass().getName());
17     }
18 }
19 
20 class Shape {
21     private String color;
22 
23     public Shape(String color){
24         this.color = color;
25     }
26 
27     public void draw() {
28         System.out.println("Color is" + getColor());
29     }
30 
31     public String getColor() {
32         return color;
33     }
34 
35     public void setColor(String color) {
36         this.color = color;
37     }
38 }
39 
40 public class TemplateTest{
41 
42     public static void main(String[] args) {
43         Template<String> ob = new Template<>("88");
44         ob.showOb();
45 
46         Template<Shape> shape = new Template<>(new Shape("RED"));
47         shape.showOb();
48     }
49 }

输出结果:

ob的类型是:java.lang.String
ob的类型是:Shape

这里示例了将泛型使用String和自定义的Shape分别实现了,同理可以将泛型用在接口、抽象类等等上。

原文地址:https://www.cnblogs.com/puyangsky/p/5104149.html