Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics and Inheritance recursion

Tags:

java

generics

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)

like image 773
navige Avatar asked Jun 04 '14 12:06

navige


2 Answers

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.

like image 133
Andremoniy Avatar answered Oct 01 '22 05:10

Andremoniy


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;
    }
}
like image 26
Oleg Sklyar Avatar answered Oct 01 '22 03:10

Oleg Sklyar