加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java继承和泛型

发布时间:2020-12-15 08:42:45 所属栏目:Java 来源:网络整理
导读:我有一些看起来像这样的类: 模型 public abstract class BaseEntityO extends Object { ... }public class Person extends BaseEntityPerson { ... } 命令 public abstract class BaseCommandBE extends BaseEntityBE { ... }public class PersonCommand ex
我有一些看起来像这样的类:

模型

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

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

命令

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

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

服务

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

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

服务进展

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

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

PersonServiceImpl类不会编译.它没有意识到create()方法正在从BaseService接口实现create()方法.任何人都可以告诉为什么PersonCommand没有被识别为BaseCommand< BE> (在参数列表中)?

解决方法

覆盖时,方法参数不是协变的(也就是说,子类必须接受超类也接受的类型,而不是更窄的类型).

这是因为人们可以通过PersonService接口使用PersonServiceImpl,它接受类型为BaseCommand< Person>的参数.这不一定是PersonCommand(想象一下,如果你创建了第二个扩展BaseCommand< Person>的类).

如果你使你的方法采用BaseCommand< Person>类型的参数,你的代码应该正确编译.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读