Java Program on Generic Methods
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Program 1
package dataflair;
class MyGen<T extends Number>
{
T ar[];
MyGen(T ar[])
{
this.ar=ar;
}
void sumofElements()
{
double s=0.0;
for(int i=0;i<ar.length;i++)
{
s=s+ar[i].doubleValue();
}
System.out.println("Sum of elements is: "+s);
}
}
public class TestMain1
{
public static void main(String[] args)
{
Integer I[]={10,20,30,40,50};
Double D[]={12.22,22.44,55.66,88.99};
Byte B[]={12,4,55,66,10};
String S[]={"a","b"};
MyGen<Integer>M1=new MyGen<Integer>(I);
MyGen<Double>M2=new MyGen<Double>(D);
System.out.println("Sum of Integer");
M1.sumofElements();
System.out.println("Sum of Double");
M2.sumofElements();
MyGen<Byte>M3=new MyGen<Byte>(B);
System.out.println("Sum of Byte");
M3.sumofElements();
}
}
We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

