Java Program on Generic Methods

Free Java courses with 37 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();
             
                                     
             
             
       }
}

 

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *