java - 继承类型转换编译错误

标签 java inheritance arraylist

我试图理解继承和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/

相关文章:

java - 使用迭代器从列表中删除条目

Java:使用 ArrayList 创建堆栈

android - ItemizedOverlay 只显示第一个条目

java - interviewstreet.com - 字符串相似度

java - NotAMockException 而 Mockito.verify(Object,VerificationMode.atleast(2))

具有父类(super class)和子类签名的 Java 2 函数 - 尽 pipe 类的类型是子类,但仍选择父类(super class)

C#,实现子类定义的具体变量的抽象父类(super class)?

java - 无法使用java邮件客户端发送邮件

java - 在我的 Spring MVC Magnolia 模块中获取 JCR Session 对象的更好方法是 LifeTimeJCRSessionUtil

java - 在运行时,查找 Java 应用程序中扩展基类的所有类