Generics : Bounded Types

In generics, the type parameters could be replaced by any class type. But in some scenarios, we would like to set a boundary on the class types.

Lets consider one such scenario. Suppose we want to concatenate a string to the object. Lets see the generic class defined below :

public class BoundedTypeClass<T> {
    T obj;
    BoundedTypeClass(T o) {
        obj = o;    }

    T getObj() {
        return obj;    }

    public void concate() {
        obj.concat("Done");    }

    public void show() {
        System.out.println("The type of obj is : " + obj.getClass().getName());    }
}

Now concat() is a method only available to Strings. This results into a compilation error : cannot find concat() for type T.

Another scenarios where errors can occur are when we pass Strings in a method that computes the average of integers.

For this example, to only accept strings, we need to bind the type. i.e. we need to extend T with a superclass that will serve as a upper boundary for the type  parameter. What that means is that any object of the superclass or any of its subclasses are valid type parameters.

To solve the above issue, we extend T with String as follows:

public class BoundedTypeClass<T extends String> {
    T obj;
    BoundedTypeClass(T o) {
        obj = o;    }

    T getObj() {
        return obj;    }

    public void concate() {
        obj.concat("Done");    }

    public void show() {
        System.out.println("The type of obj is : " + obj.getClass().getName());    }
}

That solves the compilation error. Now lets use this class with bounded types.

BoundedTypeClass<String> myG1 = new BoundedTypeClass<String>("Sandeep");System.out.println(myG1.getObj());myG1.show();
BoundedTypeClass<Integer> myG2 = new BoundedTypeClass<Integer>(100);System.out.println(myG2.getObj());myG2.show();

The first block using type parameter as String works fine. But the second block that tries to use Integer as the type parameters gives compilation error : Integer is not in bound of String.

The code for the above examples can be found here.

Bound types are not just bound to a single class, they can be bound to multiple classes & interfaces as below :

public class MultipleBoundedTypeClass<T extends String & Runnable & Comparable<String>> {

public class MultipleBoundedTypeClass<T extends Runnable>

The above two work fine. Below line should give an error since we extend classes first and then implement interfaces.

public class MultipleBoundedTypeClass<T extends Runnable & String> {

The code for multiple bounding types can be found here.

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures