I lately wanted to learn more about generic methods and created several examples, but the following type safety is not clear to me. Here an example:
public class GeneralMethod
{
public static void main( String[] args )
{
Repository rep = new Repository();
Set<ConcreteObject> set = rep.getObject();
}
}
abstract class AbstractRepository
{
public abstract <T extends SuperObject> Set<T> getObject();
}
class Repository extends AbstractRepository
{
@Override
public Set<ConcreteObject> getObject() //<- Type safety!
{
return new HashSet<ConcreteObject>();
}
}
abstract class SuperObject
{
}
class ConcreteObject extends SuperObject
{
}
Following Type safety comes up in Repository.class
in eclipse:
Type safety: The return type Set < ConcreteObject > for getObject() from the type Repository needs checked conversion to conform to Set < SuperObject > from the type AbstractRepository
Why does the compiler want to conform to Set < SuperObject > instead of Set < T extends Superobject >
?
How would you tell every Repository to implement a getObject()
method with its own type with only using generics in method signature? (meaning without defining the generic in class signature).
thank you, ymene