以 base class 作为参数的方法覆盖错误

Method overriding error with base class as an argument

我有以下代码:

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' class 作为参数吗?是什么原因? 有没有其他方法可以编写代码?

覆盖方法必须:

  • 同名
  • 具有完全相同的参数类型;子类型将不起作用!
  • 具有相同或更广泛的可见性(因此 protected -> public 是允许的,protected -> private 是不允许的)
  • 具有相同的 return 类型或子类型

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

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
    }

}

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