Java inheritance and generics

I have some classes that look like this:

Model

public abstract class BaseEntity<O extends Object> { ... }

public class Person extends BaseEntity<Person> { ... }

command

public abstract class BaseCommand<BE extends BaseEntity<BE>> { ... }

public class PersonCommand extends BaseCommand<Person> { ... }

service

public interface BaseService<BE extends BaseEntity<BE>> {
    public BE create(BaseCommand<BE> command);
}

public interface PersonService extends BaseService<Person> { ... }

Service progress

public abstract class BaseServiceImpl<BE extends BaseEntity<BE>> implements BaseService<BE> { }

public class PersonServiceImpl extends BaseServiceImpl<Person> implements PersonService {
    public Person create(PersonCommand personCommand) { ... }
}

The personserviceimpl class does not compile It does not realize that the create () method is implementing the create () method from the BaseService interface Anyone can tell why personcommand is not recognized as basecommand < be > (in the parameter list)?

Solution

When overridden, method parameters are not covariant (that is, subclasses must accept types that are also accepted by superclasses, not narrower types)

This is because people can use personserviceimpl through the personservice interface, which accepts parameters of type basecommand < person > This is not necessarily a person command (imagine if you create a second class that extends basecommand < person >)

If you make your method use parameters of basecommand < person >, your code should compile correctly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>