Generic Subclass

Java-Generic Subclass

Generic Subclass

It is perfectly acceptable for a non-generic class to be the superclass of a generic subclass. For example :

Generic Subclass

The NonGen is not generic, no type argument is specified. Thus, even though Gen declares the type parameter T, it is not needed by (nor can it be used by) NonGen. Thus, NonGen is inherited by Gen in the normal way.

Program

Generic Subclass

Program Source

class NonGen {

    private String s1;

    NonGen(String s) {
        s1 = s;
    }

    String getString() {
        return s1;
    }
}

class Gen<T> extends NonGen {

    private T t1;

    Gen(T t, String s) {
        super(s);
        t1 = t;
    }

    T getT() {
        return t1;
    }
}

public class Javaapp {

    public static void main(String[] args) {

        Gen<Integer> gobj = new Gen<Integer>(50, "Fifty");
        String s = gobj.getString();
        Integer i = gobj.getT();
        System.out.println("s -> " + s);
        System.out.println("i -> " + i);
    }
}

Leave a Comment