Covariant Return Type in Java
The term Covariant
return type means a return type of an overriding
method. It doesn’t require any type casting
, and it will help us to narrow down the return type of an overridden method.
But the Covariant
return type only works for the non-primitive
return types. This article discusses the Covariant
return type and learns the topic via example code.
Benefits of Using the Covariant
Return Type
Before we start, let’s see what benefits we get from the Covariant
return type. By using the Covariant
return type, We will get the below benefits:
- It helps us to remove the confusion on the type casts present in the class hierarchy.
- It allows us to make the code usable, readable, and easily maintainable.
- It helps us get more specific return types when overriding methods.
- It prevents the runtime exceptions like
ClassCastException
.
Demonstration of the Covariant
Return Type
In our below code example, we will illustrate the Covariant
return type. Take a look at the simple example below:
class MainClass { // Declaring a main parent class
MainClass get() { // Creating a method for the parent class
System.out.println("A message from the main class: MainClass");
return this;
}
}
// Our controlling class
public class CovariantType extends MainClass { // This class inherit to the parent class
CovariantType get() { // Overriding the parent class method
System.out.println("A message from the main class: SubClass");
return this;
}
public static void main(String[] args) {
MainClass test = new CovariantType(); // Covariant return type. No type casting is required.
test.get(); // Calling the method
}
}
We have already described the purpose of each line of code. In the example above, we first created the main class named MainClass
, which is also the parent class, and after that, we declared a method get()
and defined it.
In our child class CovariantType
, we inherited it with the parent class MainClass
and overridden the parent class’s get()
method.
Lastly, we created a Covariant
type and called the method get()
. When you execute the above example code, you will get the below output in your console.
A message from the main class: SubClass
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn