How to extend a bounded type in java

766 views Asked by At

How do we extend a bounded generic type in Java? For example, I have an abstract class as below:

public abstract class Entry<K, V extends EntryIterable<V>> {
    private Entry<K, V> next;
    private Entry<K, V> previous;
    private K key;
    private V value;
}

Let's say I have a couple of methods that I would like to implement in the subclass. So when I try to extend this class I get the below error message.

public class Record<K, V> extends Entry<K, V> {
    public Record(K key, V value) {
        super(key, value);
    }
}

ERROR: Bound mismatch: The type V is not a valid substitute for the bounded parameter <V extends EntryIterable<V>> of the type Entry<K,V>

Please help. Let me know if I made a mistake.

2

There are 2 answers

0
Jonathan On

In Entry class, you expect V type to extends EntryIterable<V>. So in Record and all its subclasses, as it extends Entry, you must ask V to extends EntryIterable<V> as well.

That's said, this will work:

public class Record<K, V extends EntryIterable<V>> extends Entry<K, V> {

You could also have stronger type. I mean, if you have a class EntryIterableAndRemovable that extends EntryIterable, you could do:

public class Record<K, V extends EntryIterableAndRemovable<V>> extends Entry<K, V> {
0
SergGr On

You should copy V extends EntryIterable<V> to the Record or else the compiler can't be sure that this restriction always holds for all Entry subclasses:

public class Record<K, V extends EntryIterable<V>> extends Entry<K, V> {