3

I'm trying to wrap my head around this inheritance problem I'm having. Here's my current situation:

enter image description here

So I have a planning that can be either a list of activities (class Activities) or a list of things to do (class Todos).
However, if I do this in Todos:

private List<Todo> todos;

public List<Activity> getPlanning(){
    return todos;
}

It says that the types are incompatible.

  • Why are they incompatible?

Since Todo extends from Activity, aren't we certain that Todo provides at least the same functionality as Activity?

and perhaps more importantly:

  • How do I adjust my design to make things work?

(I'm not an expert in UML so forgive me if there are some mistakes in my diagram)

Aerus
  • 4,332
  • 5
  • 43
  • 62

2 Answers2

5

Welcome to the nightmare and poor implementation of generics in Java. Try using public List<? extends Activity> getPlanning().

keyser
  • 18,829
  • 16
  • 59
  • 101
Augusto
  • 28,839
  • 5
  • 58
  • 88
2

If Java allowed you to return your List<Todos> as a List<Activity, the caller could then add any Activity into it. Clearly, that must not be allowed to happen.

You could make the returned list read-only by changing the return type to List<? extends Activity>. This would disallow adding any objects to the list (except null or objects directly retrieved from the same list).

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436