0

I have an created an Interface HTMLlizeable and implemented this Interface in currently two classes (Course implements HTMLlizeable and Student implements HTMLlizeable)

The loadAll Method looks like this :

public ArrayList<Course> loadAll(){...}

Now if i try to compile this line

ArrayList<HTMLlizeable>courses=this.db.getCourseLoader().loadAll();

javac or eclipse in my case always gives me this error ...

Cannot cast from ArrayList<Course> to ArrayList<HTMLlizeable>

.. and i have no idea why because Course implements HTMLlizeable. What am I doing wrong - or is this a limitation of the Generics in Java. The same thing happens btw with Student too.

T.Furholzer
  • 199
  • 1
  • 8
  • 1
    Short answer: "learn java". Java generics are not C++ templates. `List` is not `List`. Browse to here and read: https://docs.oracle.com/javase/tutorial/ There is a section on Generics. – DwB Nov 13 '17 at 14:14
  • @DwB - I'd imagine that the entry-level tutorial won't cover the issue of covariance, though. – Oliver Charlesworth Nov 13 '17 at 14:16
  • Imagine this, The `Course` and `Student` classes can have additional methods than `HTMLlizeable`, How are those methods reachable if you are casting it to HtmlLizeable? – ajc Nov 13 '17 at 14:17
  • @ajc - How is that concern different to the case of a straightforward `HTMLlizeable h = new Course(...)`? – Oliver Charlesworth Nov 13 '17 at 14:19
  • Found a simple solution. ArrayList extends HTMLlizeable>. This works. – T.Furholzer Nov 13 '17 at 14:22
  • @T.Furholzer - Be careful with that, though. You won't be able to do (for example) `courses.add(new Course(...))` if `courses` is of type `ArrayList extends HTMLlizeable>`. – Oliver Charlesworth Nov 13 '17 at 14:24

0 Answers0