Say I have these two ArrayLists:
ArrayList<Book> book = new ArrayList<>();
ArrayList<Journal> journal = new ArrayList<>();
Book and Journal are two different classes.
Both Book and Journal objects have a getYear() method. I want to make a method that passes in an unknown ArrayList type and compares a passed in year to an object in the list. The following code is in main:
public static void fooBar(int year, ArrayList<?> list)
{
if(list.get(0).getYear() == year) // does not work!
{
}
}
If an unknown type is passed into the method, I cannot use that object's methods (getYear()). How can I do this without making two methods that do the same thing (one for Book and one for Journal)?
BookandJournalshare a superclass or interface that definesgetYear()?