Search code examples
arraylistsubclasssuperclass

Creating an ArrayList of Subclass Objects


I have a superclass Appointment that is then extended to a few different types of appointments. I need to make an ArrayList of appointments of different types which I did not think would be much of a problem since they all share a common superclass - Appointment. But when I try to add one of the subclasses Daily to the ArrayList<Appointment> book = new ArrayList<Appointment>() it fails to do so.

I have:

ArrayList<Appointment> book = new ArrayList<Appointment>()

Then later on in the program (I'm passing description, day, month, and year from the method it's place in):

book.add(new Daily(description, day, month, year));

And I get the suggestion of: The method add(AppointmentBook.Appointment) in the type ArrayList is not applicable for the arguments (Daily)


Solution

  • Change your code from ArrayList<Appointment> to ArrayList<? extends Appointment>