Java 泛型 不同类型数相加

文件名 Add.java

import com.sun.corba.se.impl.orb.ParserTable.TestBadServerIdHandler;

public class Add{
    public <T extends Number> double add(T t1, T t2) {
        double allsum;
        allsum = t1.doubleValue() + t2.doubleValue();
        return allsum;
    }
    public void testAdd() {
        int int1 = 1;
        int int2 = 2;
        System.out.println("Integer sum is: " + add(int1, int2));

        long long1 = 100;
        long long2 = 200;
        System.out.println("Long sum is: " + add(long1, long2));

        float f1 = 1.0f;
        float f2 = 2.0f;
        System.out.println("Float sum is: " + add(f1, f2));

        double d1 = 1.0;
        double d2 = 2.0;
        System.out.println("Double sum is: " + add(d1, d2));
    }
    public static void main(String[] args) {
        Add my=new Add();
        my.add(10,2.5f);
        my.testAdd();
    }

}
    原文作者:你看这人,真菜
    原文地址: https://blog.csdn.net/qq_43584847/article/details/96697964
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞