Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a java method implementing a base class method return an inherited class?

Let's say I have the standard Draw class with inherited classes of Circle and Square. Is there a way to do the following? Maybe with generics?

class Draw {
  public abstract Draw duplicate();
}

class Circle extends Draw {
  public Circle duplicate() {
    return new Circle();
  }
}

class Square extends Draw {
  public Square duplicate() {
    return new Square();
  }
}
like image 577
David Thielen Avatar asked Dec 17 '13 21:12

David Thielen


2 Answers

Yes, it is possible to have an overriding method return a type that is a subclass of the superclass method's return type. This technique, called "covariant return types", is described at the bottom of a Java tutorial on return types. This works because a Circle and a Square are Draws, so even if you have a superclass reference, and you don't know or care which subclass you really have, you still are guaranteed to get back a Draw.

Incidentally, to get your code to compile, you just need to make the Draw class abstract. Everything else, including the covariant return types, looks fine.

like image 107
rgettman Avatar answered Nov 15 '22 01:11

rgettman


Yes, you can since Java 5.

Since Java 5, a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. (source). This is called covariant return types.

like image 29
Enno Shioji Avatar answered Nov 15 '22 01:11

Enno Shioji