Covariant Method Return Types in Java

Intro

I was reading the other day while enjoying some quiet time post Christmas (AWS, Spring Boot, Java) and came across something that I didn’t know existed and wanted to share.  I’m sure veteran Java programmers know this but coming from C#, I was totally unaware.

What is a Covariant Return Type?

Simply put, it is the ability of a subclass which overrides a method to return the inherited class’ type instead of the super type.

Let’s set up some code to take a look

What I’ve done above is defined a Vehicle base class that has two classes (Car and Truck) that extend.  Inside of each of those, they have a method which is abstract on the base class called getFuel()Notice that getFuel()returns a class of type Fuel.  Without covariant return types, the classes that extend Vehicle would need to have a method signature indicating that they would be returning a Fuel.  And then in any subsequent uses of that would need to perform a cast on the Fuel object into the proper runtime Fuel to do any kind of operations as they relate to that class.

Why Does this Matter?

This might seem very subtle and the surface perhaps it is.  But I’d challenge that it helps make our code more readable by providing two things

  1. Explicitness in the actual return type in the derived class.  Anytime you can make code easier to read and reason-about I thin you’ve done a good thing
  2. When working with the value of the method call, not having to cast the object to your specific subclass.  Again, more readable and maintainable.

Code that is more readable and maintainable is paramount over most everything else in a codebase.

If you want to see the full example, checkout the code over at Github

facebooktwittergoogle_plusredditpinterestlinkedinmail

About the author

Ben Pyle is a software developer who enjoys solving problems and delighting customers with right quality software. He's a husband, father to 2 boys and avid golfer. In his free time he enjoys reading, playing lots of golf and hanging out with his family doing whatever they are into.

Leave a Reply

Your email address will not be published. Required fields are marked *