创建子类对象的 ArrayList
Creating an ArrayList of Subclass Objects
我有一个超类 Appointment
,然后扩展到几个不同类型的约会。我需要创建一个包含不同类型约会的 ArrayList,我认为这不是什么大问题,因为它们都共享一个公共超类 - Appointment
。但是,当我尝试将子类之一 Daily
添加到 ArrayList<Appointment> book = new ArrayList<Appointment>()
时,它失败了。
我有:
ArrayList<Appointment> book = new ArrayList<Appointment>()
稍后在程序中(我从它所在的方法中传递描述、日、月和年):
book.add(new Daily(description, day, month, year));
我得到以下建议:类型 ArrayList 中的方法 add(AppointmentBook.Appointment) 不适用于参数(每日)
将代码从 ArrayList<Appointment>
更改为 ArrayList<? extends Appointment>
我有一个超类 Appointment
,然后扩展到几个不同类型的约会。我需要创建一个包含不同类型约会的 ArrayList,我认为这不是什么大问题,因为它们都共享一个公共超类 - Appointment
。但是,当我尝试将子类之一 Daily
添加到 ArrayList<Appointment> book = new ArrayList<Appointment>()
时,它失败了。
我有:
ArrayList<Appointment> book = new ArrayList<Appointment>()
稍后在程序中(我从它所在的方法中传递描述、日、月和年):
book.add(new Daily(description, day, month, year));
我得到以下建议:类型 ArrayList 中的方法 add(AppointmentBook.Appointment) 不适用于参数(每日)
将代码从 ArrayList<Appointment>
更改为 ArrayList<? extends Appointment>