Karl S.
Karl S.

Reputation: 355

Extending a generic type while introducing another type parameter

I have some code that doesn't compile with JDK10.
I reduced it to the example below:

abstract class Base<C extends Comparable<C>> {
    C c;
    protected Base(C c) {
        this.c = c;
    }
}

class Derived<O extends Object> extends Base<String> {
    Derived(String s) {
        super(s);
    }
}

class Scratch {
    private static void printString(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        var d = new Derived("s");
        printString(d.c);
    }
}

When I call printString(d.c) the compiler complains with Error:(21, 22) incompatible types: java.lang.Comparable cannot be converted to java.lang.String.

If I change
class Derived<O extends Object> extends Base<String> {
to
class Derived extends Base<String> {
the code works as intended.

How can I fix the code (so that d.c is of type java.lang.String) while keeping the type parameter O on the Derived type?

Upvotes: 0

Views: 54

Answers (1)

When you declare class Derived<O extends Object> but then initialize it as just new Derived, it becomes a raw type, which kills all of the generics. To fix it, initialize it with new Derived<Object> or new Derived<String> or something instead.

Upvotes: 5

Related Questions