Search code examples
javagenericsinheritancenested-generics

Casting in Java with hierachy of generics


These are my classes definition:

public interface Entity ...
public abstract class EntityBaseClass implements Entity  ...
public class ArticleCategory extends EntityBaseClass ...

And

public interface GenericService<T extends Entity> 
public interface ArticleCategoryService extends GenericService<ArticleCategory>
public class ArticleCategoryServiceImpl implements ArticleCategoryService

Why can't I do something like this:

GenericService<Entity> x = new ArticleCategoryServiceImpl(); 

?


Solution

  • Because ArticleCategoryServiceImpl implements ArticleCategoryService which extends GenericService<ArticleCategory> which is not the same as GenericService<Entity>.

    You should look at the object being instantiated for polymorphism not the generics it uses.

    You can declare x as GenericService<ArticleCategory> though. Which may better since ArticleCategory> can do as much as an Entity and then some.