Search code examples
javagenericscovariancecontravariance

Using subtype as type parameter in class


Consider the following code snippets

    public static <T> String typeName1(Class<T extends Object> c) {
        return c.getSimpleName();
    }
    public static  String typeName2(Class<? extends Object> c) {
        return c.getSimpleName();
    }

First one is showing a compile time error, while second one compiles successfully. Why is it so?


Solution

  • Change the first one to this:

    public static <T extends Object> String typeName(Class<T> c) {
        return c.getSimpleName();
    }
    

    and it will work. That's the difference in where you put the bounds. For type parameter, you declare bounds where you declare the type parameter, and not where you use it. While for wildcards, since there is no such declaration, you give bounds as and where you use it. BTW, <T extends Object> can just be <T>.

    public static <T> String typeName(Class<T> c) {
        return c.getSimpleName();
    }