我试图理解继承和ArrayList是如何工作的,所以我有以下代码 它有一个类,它将保存数据的数据库
public class Database {
ArrayList<Student> students;
ArrayList<Course> courses;
public boolean doesIDExist(ArrayList<RegistrationSystem> array, int id){
boolean exist = false;
for (RegistrationSystem array1 : array) {
if (array1.getId() == id) {
exist = true;
break;
}
}
return exist;
}
public boolean addStudent(int id, String name, String surname){
if( doesIDExist(students, id)){
return false;
}
students.add(new Student(id, name, surname));
return true;
}
}
Student和Course都是Registration System的子类
public class RegistrationSystem {
protected int id;
public int getId() {
return id;
}
}
但是我在这一行中收到错误:
if( doesIDExist(students, id))
incompatible types: ArrayList< Student > cannot be converted to ArrayList< RegistrationSystem >
我不太明白为什么会出现这个错误!
最佳答案
您的方法需要一个 RegistrationSystem
列表,而不是 Student
列表。
您必须更改为:
public boolean doesIDExist(ArrayList<? extends RegistrationSystem> array, int id){
关于java - 继承类型转换编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29965312/