Search code examples
javagenericsgraphabstract-classfactory-pattern

Does the return value of an abstract method can be of generic type


the first part of my project is to construct an hypergraph

This is a quickly-drew UML diagram enter image description here

The vertex class

    public abstract class Vertex <T>{

int vertexId ;
T vertexValue ;

public  abstract <T> T setVertexValue();

    }

The imageVertex class

   public class ImageVertex extends Vertex<Map<String, Instance>>{

@Override
public <T> T setVertexValue() {
    // TODO Auto-generated method stub
    return null;
}}

I has thought that Type will be inferred automatically as i define it for the imageVertex Map and later for tagVertex as String

had I wrongly used the generics?


Solution

  • You've redefined the type T on setVertexValue. Use this.

    public abstract class Vertex <T>{
    
    int vertexId ;
    T vertexValue ;
    
    public  abstract T setVertexValue();
    
    }
    

    It uses the generic properly

    public class ImageVertex extends Vertex<Map<String, String>>
    {
    
        @Override
        public Map<String, String> setVertexValue()
        {
            // TODO Auto-generated method stub
            return null;
        }
    
    }