Search code examples
javatypespolymorphismjung

Why do I get a type mismatch during compile time


I'm declaring a graph (using JUNG's Graph interface) as a class variable like this:

private Graph<Knoten, Kante> _graph;

I try to initialize it like this:

_graph = new DirectedSparseGraph<AttrKnoten, GewKante>();

AttrKnoten extends Knoten and GewKante extends Kante (they are just marker interfaces at the moment). I get the following error message during compile time:

"Type mismatch: cannot convert from DirectedSpareGraph<AttrKnoten, GewKante> to Graph<Knoten, Kante>"

Why is that? Is there any other way to handle this, but leaving out the parameters during declaration?


Solution

  • You can't do that with generics.

    A simpler example:

    List<CharSequence> list = new ArrayList<String>();
    

    This doesn't work, even though String implements CharSequence.


    The easiest solution is to just do:

    _graph = new DirectedSparseGraph<Knoten, Kante>();
    

    You can still add AttrKnoten and GewKante objects to _graph.


    Alternatively, if you only want AttrKonten and GewKante objects, just declare it as:

    private Graph<AttrKnoten, GewKante> _graph;