I am trying to create a set up where a set of subclasses override a superclass. This superclass contains an abstract method – the return type of which would ideally be that of the object from which this method was called, such that it effectively behaves like this:
public abstract class SuperClass{
public abstract SuperClass getSelf();
}
public class SubClass extends SuperClass{
@Override
public SubClass getSelf(){
return this;
}
}
I am unsure if such a thing is possible, as I think return types always have to be the same in order for the override to work – however I have been thinking the answer, should one exist, lies somewhere along this line…
public abstract class SuperClass{
public abstract <? extends SuperClass> getSelf();
}
public class SubClass extends SuperClass{
@Override
public SubClass getSelf(){
return this;
}
}
Thanks for any help.
edit: added extends SuperClass to SubClass, duh
This will work:
Notice I’ve added
extends SuperClassto yourSubClassdefinition. The return type ofgetSelfis referred to as a covariant return type.