Sum with Generic in Java


Sum Class

Create generic package. In this package, create new java class named Sum as below:

package generic;

public class Sum<T extends Number, K extends Number> {

	private T number1;
	private K number2;

	public T getNumber1() {
		return number1;
	}

	public void setNumber1(T number1) {
		this.number1 = number1;
	}

	public K getNumber2() {
		return number2;
	}

	public void setNumber2(K number2) {
		this.number2 = number2;
	}

	public Sum() {
	}

	public Sum(T number1, K number2) {
		this.number1 = number1;
		this.number2 = number2;
	}

	public <V extends Number> V sum() {
		if (this.number1 == null || this.number2 == null) {
			return null;
		}
		if (this.number1 instanceof Double && this.number2 instanceof Double) {
			return (V) new Double(this.number1.doubleValue() + this.number2.doubleValue());
		} else if (this.number1 instanceof Integer && this.number2 instanceof Integer) {
			return (V) new Integer(this.number1.intValue() + this.number2.intValue());
		} else if (this.number1 instanceof Integer && this.number2 instanceof Double) {
			return (V) new Double(this.number1.intValue() + this.number2.doubleValue());
		} else if (this.number1 instanceof Double && this.number2 instanceof Integer) {
			return (V) new Double(this.number1.doubleValue() + this.number2.intValue());
		} else {
			throw new IllegalArgumentException("Type is not supported by this method");
		}
	}

}




package generic;

public class Main {

	public static void main(String[] args) {

		Sum<Integer, Integer> sum1 = new Sum<Integer, Integer>(3, 5);
		System.out.println("Sum 1: " + sum1.sum());

		Sum<Double, Double> sum2 = new Sum<Double, Double>(2.6, 5.3);
		System.out.println("Sum 2: " + sum2.sum());

		Sum<Integer, Double> sum3 = new Sum<Integer, Double>(2, 5.3);
		System.out.println("Sum 3: " + sum3.sum());

		Sum<Double, Integer> sum4 = new Sum<Double, Integer>(2.6, 4);
		System.out.println("Sum 4: " + sum4.sum());

	}

}
Sum 1: 8
Sum 2: 7.9
Sum 3: 7.3
Sum 4: 6.6