Inherited method returned reference type

generics, inheritance, java

Solution

No cast, no @SuppressWarning, few lines only:

public abstract class SuperClass<T extends SuperClass<T>> {
    protected T that;
    public T chain() {
        return that;
    }
}

public class SubClass1 extends SuperClass<SubClass1> {
    public SubClass1() {
        that = this;
    }
}

public class SubClass2 extends SuperClass<SubClass2> {
    public SubClass2() {
        that = this;
    }
}

Problem

I'm facing the problem described in this question but would like to find a solution (if possible) without all the casts and @SuppressWarning annotations. A better solution would be one that builds upon the referenced one by: - removing @SuppressWarning - removing casts Solutions presented here will be graded with 2 points based on the criteria. Bounty goes to solution with most points or the "most elegant" one if there is more than one with 2 points.

Original source

Related problems