I came across the following Java code that uses generics and inheritance. I truly do not understand what the following snippet does:
class A<B extends A<B>> {
...
}
What does this code do?
(I got this from DBMaker in MapDB)
It is almost clear and the question actually conists in two parts:
1) why B extends A
?
2) why A
inside B extends A<B>
has generic type B
?
Answers for these parts will be:
1) In particular example this class (A
) is builder class (called DBMaker
), so most of its methods return some type, which extends this builder's class type. This explains, why B
should extend A
class.
2) But, actualy, if we will hide for the second part ...extends A<B>
, we will receive just class A<B>
. So A
has type variable of type B
. That is why in ...extends A<B>
A is marked as type A
having type variable B
.
This tells that A
needs derived definitions to be able to do some work:
public abstract class A<T extends A<T>> {
protected T instance;
T getOne() {
return instance;
}
}
public class B extends A<B> {
public B() {
instance = this;
}
}
public static void test() {
B b = new B();
b.getOne();
}
This is most commonly used in interface definitions, where one wants to explicitly use instances of classes implementing an interface in return types or in arguments and not the interface itself:
public interface TimeSeries<T extends TimeSeries<T>> {
T join(T ts);
}
public class DoubleTimeSeries implements TimeSeries<DoubleTimeSeries> {
@Override
public DoubleTimeSeries join(DoubleTimeSeries ts) {
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With