Java Generic Bounded Types

In this chapter you will learn:

  1. What is Java Generic Bounded Types
  2. Syntax for Generic Bounded Types
  3. Example - 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;//from  w  w w.j  a v a 2 s  . c om
  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.

Next chapter...

What you will learn in the next chapter:

  1. What is generic method
  2. Example for generic method
  3. Example - copyList() generic method
Home »
  Java Tutorial »
    Java Langauge »
      Java Generics
Java Generic Type
Java Generic Bounded Types
Java Generic Method
Java Generic Constructors
Java Generic Parameter Wildcard
Java Generic interface
Java Raw Types and Legacy Code
Java Generic Class Hierarchies
Java generic types cast
Java Generic Restrictions