码迷,mamicode.com
首页 > 编程语言 > 详细

java 泛型

时间:2018-10-20 23:48:01      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:private   out   不能   div   void   泛型   interface   泛型方法   print   

只能使用引用类型, 不能使用基本类型(int 与 Integer)

泛型类

class Point<T>{
    private T a;
    private T b;
    public Point(T a, T b){
        this.a = a;
        this.b = b;
    }
    public void say(){
        System.out.println("a: " + a + ", b: " + b);
    }
}
public class Test3 {
    public static void main(String[] args) {
        Point<Integer> point1 = new Point<>(1, 2);
        point1.say();
        Point<String> point2 = new Point<>("hello", "world");
        point2.say();
    }
}

泛型接口

interface IPoint<T>{
    void say(T t);
}
class PointImpl1 implements IPoint<String>{
    @Override
    public void say(String s) {
        System.out.println(s);
    }
}

class PointImpl2<T> implements IPoint<T>{
    @Override
    public void say(T t) {
        System.out.println(t);
    }
}
public class Test3 {
    public static void main(String[] args) {
        IPoint p1 = new PointImpl1();
        p1.say("Hello");
        IPoint<Integer> p2 = new PointImpl2<>();
        p2.say(1);
    }
}

泛型方法

public static void main(String[] args) {
        String s = say("hello");
        System.out.println(s);
    }

    // 返回类型由参数决定
    public static <T> T say(T t){
        return t;
    }

 

java 泛型

标签:private   out   不能   div   void   泛型   interface   泛型方法   print   

原文地址:https://www.cnblogs.com/huanggy/p/9823390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!