Java Program to add two numbers using generics.
Objective
Write a Java program to add two numbers of any numeric type using Generics.
Algorithm / Approach
- Create a class
Test<T extends Number>. - Create a method
add(T a, T b). - Convert both generic numbers to doubles using
doubleValue()and add them. - In main, instantiate the class for
Integer,Float, andDoubletypes and calladd().
Test.java
class Test<T extends Number> {
void add(T a, T b) {
double c=a.doubleValue()+b.doubleValue();
System.out.println(c);
}
public static void main(String[] a)
{
Test<Integer> t1=new Test<Integer>();
Test<Float> t2=new Test<Float>();
Test<Double> t3=new Test<Double>();
t1.add(4,5);
t2.add(2.5f,3.5f);
t3.add(4.5,7.9);
}
}
Expected Output
9.0 6.0 12.4
Explanation of the Program
- Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.
- The syntax
<T extends Number>is a Bounded Type Parameter. It restricts the generic typeTto only be a subclass of thejava.lang.Numberclass. - Because we bounded it to
Number, we can safely call thedoubleValue()method onaandb, allowing us to perform universal math regardless of whether the user passed an Integer or a Float.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)