In: Computer Science
IN JAVA, For this exercise, you will create your own example of using a generic method. First write a program that calls a method to multiply two integers and return the integer result. Then modify that program to make the method generic, calling it with two generic data types (T1 and T2) and then returning the result in the same type (also needs to be generic). Demonstrate your program by calling the method two times, once with an integer and once with a double. In your main program, display the results of the method call showing both an integer output and a decimal output. Submit code for both your original method (non-generic) and your revised method (generic), along with execution screenshots.
// do comment if any problem arises
//code
This is for original/non-generic method:
class Multiplication {
// Method to multiply 2 integers
static int multiply(int a,int b)
{
return a*b;
}
public static void main(String args[]) {
// print 3 x 4
System.out.println("3 x 4 = "+multiply(3, 4));
}
}
Output:
For generic method:
class Multiplication {
// Method to multiply 2 integers
static <T extends Number> T multiply(T a, T b) {
if (Integer.class.isInstance(a))
return (T) Integer.valueOf(a.intValue() * b.intValue());
else
return (T) Double.valueOf(a.doubleValue() * b.doubleValue());
}
public static void main(String args[]) {
// print 3 x 4
System.out.println("3 x 4 = " + multiply(3, 4));
// print 3.1 x 4.6
System.out.println("3.1 x 4.6 = " + multiply(3.1, 4.6));
}
}
Output: