Java Generics Bounded Types

Introduction

For type parameter, we can set an upper bound.

The upper bound declares the superclass from which all type arguments must be derived.

superclass defines an inclusive, upper limit.

<T extends superclass> 

class MyArray<T extends Number> {  
  public T[] nums; // array of Number or subclass 
    //from  w  w  w .j a va  2 s  . co  m
  // Pass the constructor a reference to   
  // an array of type Number or subclass. 
  public MyArray(T[] o) {  
    nums = o;  
  }  
  
  // Return type double in all cases. 
  public 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 }; 
    MyArray<Integer> iob = new MyArray<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 }; 
    MyArray<Double> dob = new MyArray<Double>(dnums);   
    double w = dob.average(); 
    System.out.println("dob average is " + w); 
 
 
  }  
}

Note

We can specify multiple interfaces as bounds.

A bound can include both a class type and one or more interfaces.

The class type must be specified first.

When a bound has an interface type, only type arguments that implement that interface are allowed.

To specify a bound with a class and an interface, or multiple interfaces, use the & operator to connect them.

For example,

class Gen<T extends MyClass & MyInterface> { // ... 



PreviousNext

Related