When one class implements another interface, will

2019-08-21 02:35发布

问题:

I have an generic abstract class, BString, which expects one of its types to implement Comparable. Another class, NGram extends BString, passing String as the comparable type. A final class, BinarySearchTree expects keys which extend Comparable.

Why am I unable to create a BinarySearchTree with NGram as the key type? Does the implements Comparable declaration for BString strictly hold for BString and none of its descendants? I have included the class declarations below, and note that while BString overrides compareTo, NGram does not. Below is the requested code.

public abstract class BString<Alphabet extends Comparable<Alphabet>> implements Iterable<Alphabet>, Comparable<BString<Alphabet>> {
protected FixedSizeFIFOWorkList<Alphabet> str;

}
public BString(Alphabet[] str) {
    this.str = new CircularArrayFIFOQueue<Alphabet>(str.length);
    for (int i = 0; i < str.length; i++) {
        this.str.add(str[i]);
    }
}

public class NGram extends BString<String> {
    public NGram(String[] str) {
        super(str);
    }
}

public class BinarySearchTree<K extends Comparable<K>, V>
    extends ComparableDictionary<K, V> {
    // The root of the BST. Root is null if and only if the tree is empty.
    protected BSTNode root;

    /**
     * Create an empty binary search tree.
     */
    public BinarySearchTree() {
        super();
        this.root = null;
    }
}

new BinarySearchTree<NGram,Dictionary<AlphabeticString, Integer>>()

When I go to actually create the BinarySearchTree, as in the last line of the code, I am given the following message:

Bound mismatch: The type NGram is not a valid substitute for the bounded parameter <K extends Comparable<K>> of the type BinarySearchTree<K,V>