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();
}
}
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 Draw
s, 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.
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.
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