Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 282
nawara Avatar asked Feb 16 '23 20:02

nawara


2 Answers

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;
    }

}
like image 163
Deepak Bala Avatar answered Feb 19 '23 08:02

Deepak Bala


It seems that you are trying to write:

public abstract class Vertex<T> {

    int vertexId;
    T vertexValue;

    public abstract T setVertexValue(); // NOTE: no <T>
}

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

    @Override
    public Map<String, Instance> setVertexValue() {
        return null;
    }
}

In your code, the <T> in

public abstract <T> T setVertexValue();

is a completely separate generic parameter that shadows the T in Vertex<T>.

like image 24
NPE Avatar answered Feb 19 '23 09:02

NPE