Generics: Bounded Type Parameters Tutorial

In this tutorial I will introduce you to bounded type parameters. I will expand on my example Box class by turning it into a generic class that will take values from various types of classes that are subclasses of the Number class. Classes such as Integer, Float, Double, etc. will all be valid parameter types for this new and improved version. Bounded type parameters limit the valid type parameters to only types that are an instance of the bounded type. The Java keywords extends is used to specify the bounded type.
For example,
class Box<T extends Number> { ... }
In the example above, the Number class is the bounded type specified after the extends keyword. The T is the type-variable. The T type-variable must be a subclass of Number somewhere down the hierarchy or else a compiler error will occur. Angle brackets are also known as chevrons or diamond syntax.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md GenericBounded
C:\Java>cd GenericBounded
C:\Java\GenericBounded>Notepad GenericBounded.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class GenericBounded {
    public static void main(String args[]) {
        Box<Integer> box1 = new Box<Integer>(new Integer(6), new Integer(5), new Integer(3));
        Box<Integer> box2 = new Box<Integer>(7, 2, 10); // autoboxing parameters
        Box<Float> box3 = new Box<Float>(4.25f, 3.0f, 10.0f);
        Box<Double> box4 = new Box<Double>(11.5, 5.0, 6.5);
        Box<Byte> box5 = new Box<Byte>((byte)0xA, (byte)0x13, (byte)0xB);
         
        System.out.println("The volume of box1 is: " + box1.getVolume());
        System.out.println("The volume of box2 is: " + box2.getVolume());
        System.out.println("The volume of box3 is: " + box3.getVolume());
        System.out.println("The volume of box4 is: " + box4.getVolume());
        System.out.println("The volume of box5 is: " + box5.getVolume());
    }
}

class Box<T extends Number> {
    private T length;
    private T height;
    private T width;

    Box(T length, T height, T width) {
        this.length = length;
        this.height = height;
        this.width = width;
    }

    double getVolume () {
        return (length.doubleValue() * height.doubleValue() * width.doubleValue());
    }
}

Now switch back to the command prompt (CMD) and type in javac GenericBounded.java and press Enter.
Now type in java GenericBounded and press Enter.


C:\Java\GenericBounded>javac GenericBounded.java
C:\Java\GenericBounded>java GenericBounded
The volume of box1 is: 90.0
The volume of box2 is: 140.0
The volume of box3 is: 127.5
The volume of box4 is: 373.75 
The volume of box5 is: 2090.0



Final thoughts

None


Tutorials