You are here: Home / Topics / Program to explain Generic class with Bounded type in Java

Program to explain Generic class with Bounded type in Java

Filed under: Java on 2024-04-12 18:39:04

// Program to explain Generic class with Bounded type.


//  The type argument for T must be either Number, or a 
//  class derived from Number.

class  Stats<T extends Number> 

T[ ] nums;
  
Stats(T[ ]  o) 

 nums = o; 


double average() 

 double sum = 0.0;

 for(int i=0; i < nums.length; i++) 
  sum += nums[i].doubleValue();

 return sum / nums.length;



public class  GenericTest11 

public static void main(String  args[ ]) 

 Integer inums[ ] = { 1, 2, 3, 4, 5 };
 Stats<Integer> iob = new Stats<Integer>(inums);
 double v = iob.average();
 System.out.println("iob average is " + v);

 Double dnums[ ] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
 Stats<Double> dob = new Stats<Double>(dnums);
 double w = dob.average();
 System.out.println("dob average is " + w);

}

 

Output:

iob average is 3.0
dob average is 3.3

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.