Java - Bounded Type Parameters

Java Conceptuel Diagram

About

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

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:

Example

Method

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

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;
    }

    // ...
}

Documentation / Reference





Discover More
Java Conceptuel Diagram
Java - (Generic|Parameterized) type - (Class|Interface|Method) Parametrization

and Integer.class is of type Class Stronger type checks at compile time. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find. The compiler can check the type...
Java Conceptuel Diagram
Java - Greater than Operator

The greater than operator (>) The greater than operator (>) appliesonly to primitive types such as short, int, double, long, float, byte, and char. To compare objects, use a type parameter...



Share this page:
Follow us:
Task Runner