Generic Superclass

Java-Generic Superclass

Generic Superclass

Generic classes can be part of a class hierarchy in just the same way as a non-generic class. Thus, a generic class can act as a superclass or be a subclass. The key difference between generic and non-generic hierarchies is that in a generic hierarchy, any type arguments needed by a generic superclass must be passed up the hierarchy by all subclasses. This is similar to the way that constructor arguments must be passed up a hierarchy. Following is a simple example of a hierarchy that uses a generic superclass :

Generic Superclass

The GenTwo extends the generic class GenOne. The type parameters T and V are specified by GenTwo and T is also passed to GenOne in the extends clause. This means that whatever type is passed to the first type of GenTwo will also be passed to GenOne. For example :

Generic Superclass

The Integer is passed to GenOne, and String is specific to GenTwo. Thus, the T type variables of GenOne portion of GenTwo will be of type Integer . Even if a subclass of a generic superclass would otherwise not need to be generic, it still must specify the type parameter(s) required by its generic superclass :

Generic Superclass

Program

Generic Superclass

Program Source

class GenOne<T> {

    private T t1;

    GenOne(T t) {
        t1 = t;
    }

    T getT() {
        return t1;
    }
}

class GenTwo<T,V> extends GenOne<T> {

    private V v1;

    GenTwo(T t, V v) {
        super(t);
        v1 = v;
    }

    V getV() {
        return v1;
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        GenTwo<Integer,String> gtwo = new GenTwo<>(50,"Fifty");
        Integer i = gtwo.getT();
        String  s = gtwo.getV();
        System.out.println("i -> "+i);
        System.out.println("s -> "+s);
    }
}

Leave a Comment