Java - Bounded Type Parameters

> Procedural Languages > Java

1 - About

A generic method or class that operates on numbers will used bounded type parameters to restrict the type parameters accepted.

Advertising

3 - Syntax

The extends keyword, followed by one or several upper bounds. If one of the bounds is a class, it must be specified first

<T (extends|super) B1 [& B2 & ... & Bn]>

where:

  • B1 to Bn are class or interface that defined the bounds
  • B2 to Bn are optional
  • extends defined upper bounds
  • super define lower bounds

In this context, extends is used in a general sense to mean either:

4 - Example

4.1 - Method

public <U extends Number> void inspect(U u)

4.2 - Class

public class NaturalNumber<T extends Integer> {
 
    private T n;
 
    public NaturalNumber(T n)  { this.n = n; }
 
    public boolean isEven() {
        // intValue is methods defined in the bounds
        return n.intValue() % 2 == 0;
    }
 
    // ...
}

5 - Documentation / Reference

Advertising
lang/java/bounded.txt · Last modified: 2017/02/12 21:05 by gerardnico