I have a superclass method which returns itself(for builder pattern). This class has several subclasses , so I want to return a reference to actual(subclass) type of the object. Something like this:
class SuperClass {
T someMethodThatDoesSameThingForAllSubclasses() {
// blablbal
return reference_of_actual_object;
}
}
So that I can call other subclass methods from subclass reference without casting. Like this:
SubClass obj=new SubClass();
obj.someMethodThatDoesSameThingForAllSubclasses().someSubclassMethod();
//currently this gives compiler error. because first method returns superclass reference and super class doesn't have someSubclassMethod
Is this posible and does it make sense to try to do something like this?
There's no particularly nice way of doing this, that I'm aware of. The best I've seen is just to cast - which you can do once, of course:
public class Superclass<T extends Superclass<T>> {
@SuppressWarnings("unchecked")
private final T thisAsT = (T) this;
T someMethodThatDoesSameThingForAllSubclasses() {
return thisAsT;
}
}
public class Subclass extends Superclass<Subclass> {
Subclass subclassOnlyMethod() {
return this;
}
}
And then:
Subclass subclass = new Subclass().someMethodThatDoesSameThingForAllSubclasses()
.subclassOnlyMethod();
It's horrible that the cast doesn't actually check anything due to type erasure, but that's the joy of Java generics :(