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
To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
An abstract method has no body. (It has no statements.) It declares an access modifier, return type, and method signature followed by a semicolon.
Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .
Just like type declarations, method declarations can be generic—that is, parameterized by one or more type parameters.
This will work:
public abstract class SuperClass{
public abstract SuperClass getSelf();
}
public class SubClass extends SuperClass{
@Override
public SubClass getSelf(){
return this;
}
}
Notice I've added extends SuperClass
to your SubClass
definition. The return type of getSelf
is referred to as a covariant return type.
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