Override list result type in java

I would like some version of this code to compile in java.

class X
{
    List<X> getvalue(){...};
}

class Y extends X
{
    List<Y> getvalue(){...};
}

Javac (1.6) returns an error because List <Y> and List <X> are incompatible.

The thing is, I would like the compiler to recognize that List <Y> is a compatible return of type to List <X> if Y is a subtype of X. The reason I want this is to make it easier to use a custom factory class.

Note. This question is somewhat reminiscent of this question but for java.

+3
source share
2 answers

Java .

java.util.List ( Java. - -). , B <: A List<B> <: List<A> ( <: is-subtype-of). , .


Java . typechecks:

import java.util.List;

class X {
  List<? extends X> getvalue() { return null; }
}

class Y extends X {
  List<Y> getvalue() { return null; }
}
+7

, . List<Y> List<X> , Y X. :

List<Banana> bananas = new ArrayList<Banana>();
List<Fruit> fruit = bananas;
fruit.add(new Apple());
Banana banana = fruit.get(0); // But it an apple!

Java, , , :

List<? extends Fruit> fruit = bananas;

( ) - , .

Angelika Langer Java Generics .

+6

Source: https://habr.com/ru/post/1764222/


All Articles