0

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(); 

?

David Anderson
  • 623
  • 5
  • 22

2 Answers2

1

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.

Logan Murphy
  • 6,120
  • 3
  • 24
  • 42
  • Since ArticleCategory extends Entity, why GenericService is not the same as GenericService ? – David Anderson Apr 24 '14 at 19:01
  • 1
    Well when you have GenericService vs GenericService in the background java essentially compiles 2 individual classes. One that replaces all the generic references in `GenericService` with `ArticleCategory` and another that replaces all the generic reference in `GenericService` with `ArticleCategory`. So essentially you are dealing with two completely different classes. – Logan Murphy Apr 24 '14 at 19:43
0

Consider it like this, if you would have a GenericService<Entity>, then you would have for example, a method like this: add(Entity entity), you could pass in ANY entity, even one that is not an ArticleCategory, those causing a exception when handled in the ArticleCategoryServiceImpl implementation. (Remember this implementation takes an ArticleCategory as an argument for the add method)

ArticleCategory is an Entity, but GenericService<ArticleCategory> is not a GenericService<Entity>

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154