Direct casting in foreach loop

I'm reasonably sure you cannot cast in the loop as you would like.


Think obout casting

ExtendedBook ex=(ExtendedBook)new Book();

It is accepted by compilator but JVM throws java.lang.ClassCastException, because that type of casting is wrong -> Book is not ExtendedBook, so there is a chance that it wont handle potential new methods added in ExtendedBook class.

For the same reason you can't do something like

ExtendedBook[] exbooksB=(ExtendedBook[]) new Book[10];

but can

Book[] booksA=new ExtendedBook[10];
ExtendedBook[] exbooks=(ExtendedBook[]) booksA;

How about using Generics?

Write your getBooks signature as:

<B extends Book> B [] getBooks(Class<B> bookType)

Now, if you want to search for books of the type ExtendedBook, just call:

ExtendedBooks [] eBooks = bookSearch.getBooks(ExtendedBook.class)

No typecasting or other unsafe stuff needed. Nice and clean.

Of course you still have to make sure that only ExtendedBook only returns that kind of book, but it looks like you solved that already.