What is Java Generic Bounded Types and how to use Generic Bounded Types

Description

When specifying a type parameter, you can create an upper bound from which all type arguments must be derived.

Syntax

This is accomplished through the use of an extends clause when specifying the type parameter:


<T extends superClassName>

This specifies that T can only be replaced by superClassName, or subclasses of superClassName. Thus, superclass defines an inclusive, upper limit.

Example


class Calculator<T extends Number> {
  T[] nums;/*w w  w .  j a v  a2  s  .c  o  m*/
  Calculator(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 Main {
  public static void main(String args[]) {
    Integer inums[] = { 1, 2, 3, 4, 5 };
    Calculator<Integer> iob = new Calculator<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 };
    Calculator<Double> dob = new Calculator<Double>(dnums);
    double w = dob.average();
    System.out.println("dob average is " + w);
  }
}

In addition to using a class type as a bound, you can also use an interface type. You can specify multiple interfaces as bounds.

A bound can include both a class type and one or more interfaces. In this case, the class type must be specified first.

When a bound includes an interface type, only type arguments that implement that interface are legal.

When specifying a bound that has a class and an interface, or multiple interfaces, use the & operator to connect them.

For example,


class Gen<T extends MyClass & MyInterface> {}

Any type argument passed to T must be a subclass of MyClass and implement MyInterface.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures