In this tutorial we are going to learn, What is bounded types and how to use it. See the below example.

package sree;
import java.util.Date;

public class Sample<T> {
    T t ;
    Sample(T t){
        this.t =t;
    }
    public T get()
    {
        return t;
    }
    public static void main(String[] args) {
        Sample<String> sample = new Sample<String>("welcome");
        Sample<Date> date = new Sample<Date>(new Date());
    }
}

See , from the above example we are passing ‘String’ and ‘Date’ types as type parameters. here , we can pass any type as type parameter hence it is unbounded type. Now my question is, how to restrict the generic class to allow particular type parameters only? Answer is using ‘extends’ keyword . See the below exmaple , in that we are restring the generic class to allow String and its sub classes only. If we try to pass any other type as type parameter we will get compiler error.

package sree;
import java.util.Date;

public class Sample<T extends String> {
    T t ;
    Sample(T t){
        this.t =t;
    }
    public T get()
    {
        return t;
    }
    public static void main(String[] args) {
        Sample<String> sample = new Sample<String>("welcome");
        Sample<Date> date = new Sample<Date>(new Date());// here we will get compiler error.
        //No other type is allowed except String and its child types
    }
}

We can use extends keyword with class/interface . If we use class , then the corresponding class and it’s subclasses will be allowed by generic class.
If we use interface, then it’s implemented class types will be allowed by generic class.