Topics Index

Bounded Types - Java Example Program

Bounded Types
class AverageDemo
    public static void main (String args[])
            Integer integerNumbers[] = {1, 2, 3, 4, 5};
            Average<Integer> integerObject = new Average<Integer>(integerNumbers);
            double average = integerObject.getAverage();
            System.out.println("The average value of given integers is : " + average);
            String strs[] = {"A", "B", "C", "D"};
          //  Average<String> stringObject = new Average<String>(strs); // LINE A

class Average<T extends Number> { // LINE B
    T[] numbers;
    public Average(T[] numbers)
        this.numbers = numbers;
    double getAverage()
        double sum = 0.0;
        for(int i = 0; i< numbers.length; i++)
            sum += numbers[i].doubleValue(); // LINE C
        return sum / numbers.length;

The average value of given integers is : 3.0


Here Number class acts as a super class. Without extends Number at LINE Bwe try to run the program. The compiler gives compile time error at LINE C,since all numeric classes such as Integerand Doubleare subclasses of Number,and Numberdefines doubleValue().If you uncomment the LINE Ait gives compilation error since Stringclass does not come under Numberclass.

  • Put class Average<T> instead of class Average<T extends Number>, compilation error occured at LINE C.
  • Uncomment the line at LINE Aand try to run it. It gives a compile time error.
  • Create one more object for Double in AverageDemo and print the average of {1.5, 2.1, 3.3} double array.

© meritcampus 2019

All Rights Reserved.

Open In App