Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics - overriding an abstract method and having return type of the subclass

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

like image 902
Numeron Avatar asked Jun 23 '11 07:06

Numeron


People also ask

How do you override an abstract method in a subclass?

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.

Can we have return type for abstract method?

An abstract method has no body. (It has no statements.) It declares an access modifier, return type, and method signature followed by a semicolon.

Can an abstract class have a subclass?

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 .

Can a method return a generic type?

Just like type declarations, method declarations can be generic—that is, parameterized by one or more type parameters.


1 Answers

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.

like image 96
Rob Harrop Avatar answered Oct 15 '22 15:10

Rob Harrop