我有以下代碼:
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'類作為引數嗎?是什么原因?有沒有其他方法可以撰寫代碼?
uj5u.com熱心網友回復:
覆寫方法必須:
- 有完全相同的名字
- 具有完全相同的引數型別;子型別不起作用!
- 具有相同或更廣泛的可見性(因此允許受保護 -> 公開,不允許保護 -> 私有)
- 具有相同的回傳型別或子型別
你在這里違反了第二條規則。幸運的是,您可以使用泛型來解決此問題:
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)。
uj5u.com熱心網友回復:
這就是導致您的錯誤的原因:
interface BaseRepository {
public void save(Entity entiy);
}
class StudentRepository implements BaseRepository {
@Override
public void save(Student student) {
// student validation code
// save the entity
}
}
您正在實作一個介面,該介面具有Entity作為引數的偵聽器。但是,在實施時,您將其視為Student. 根據您的需要嘗試給定的 2 個解決方案中的任何 1 個。
1.
interface BaseRepository {
public void save(Entity entiy);
}
class StudentRepository implements BaseRepository {
@Override
public void save(Entity student) {
// student validation code
// save the entity
}
}
interface BaseRepository {
public void save(Student entiy);
}
class StudentRepository implements BaseRepository {
@Override
public void save(Student student) {
// student validation code
// save the entity
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/455112.html
