Topics Index

Generics >
Siva Nookala - 07 Apr 2016
The type parameters could be replaced by any class type. This is fine for many purposes, but sometimes it is useful to limit the types that can be passed to a type parameter
Syntax :
<T extends superclass>

Bounded type parameters can be used with methods as well as classes and interfaces. Genericssupports multiple bounds also, i.e <T extends A & B & C>. In this case A can be an interfaceor class.If A is classthen B and C should be interfaces. We can’t have more than one classin multiple bounds.

Assume that you want to create a generic class that contains a method that returns the average of an array of numbers. Furthermore, you can use the class to obtain the average of an array of any type of number, including integers, floats, and doubles.
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.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.