使用基类作为参数的方法覆盖错误

我知道什么

我有以下代码:

interface Entity {
    
}
class Student implements Entity{
    
}
class Course implements Entity{
    
}

interface BaseRepository {
    public void save(Entity entiy);
}

class StudentRepository implements BaseRepository {
    @Override
    public void save(Student student) {
        // student validation code
        // save the entity
    }
}
class CourseRepository implements BaseRepository {
    @Override
    public void save(Course course) {
        // course validation code
        // save the entity
    }
}

当我尝试编译它时,给我以下错误:StudentRepository is not abstract and does not override abstract method save(Entity) in BaseRepository

java不接受'Base'类作为参数吗?是什么原因?有没有其他方法可以编写代码?

罗布·斯波

覆盖方法必须:

  • 有完全相同的名字
  • 具有完全相同的参数类型;子类型不起作用!
  • 具有相同或更广泛的可见性(因此允许受保护 -> 公开,不允许保护 -> 私有)
  • 具有相同的返回类型或子类型

你在这里违反了第二条规则。幸运的是,您可以使用泛型来解决此问题:

interface BaseRepository<E extends Entity> {
    public void save(E entiy);
}

class StudentRepository implements BaseRepository<Student> {
    @Override
    public void save(Student student) {
        // student validation code
        // save the entity
    }
}
class CourseRepository implements BaseRepository<Course> {
    @Override
    public void save(Course course) {
        // course validation code
        // save the entity
    }

}

现在, aBaseRepository<Student>应该覆盖的方法不是public void save(Entity)but public void save(Student)同样, aBaseRepository<Course>应该覆盖的方法不是public void save(Entity)but public void save(Course)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章