Covariance means that the return types must be of similar type and not of very different type. Covariant return types in Java are described as the ability that a subclass possesses to override the method of its superclass. It returns a specific type as compared to the return type of the method that was overridden. Java has allowed the use of covariant return types since the release of JDK5.0. If you try to run the covariant types on the version before this release, the program will not be compiled.
This article will demonstrate how to handle covariant return types in Java.
How to Handle/Manage Covariant Return Type in Java?
The covariant return type helps in making a clean and usable code. Since a clean code helps in the development of large applications. There are some important points to note that:
- Use covariant return type with non-primitive data types like arrays, lists, and classes.
- The return type method of a child must be a subtype of its parent method’s return type.
To have a clear understanding there is pictorial a representation of covariant types in Java depicted below:
Pictorial Representation
The covariant return type can be easily understood by the following pictorial representation.
In this image the Supertype method has been overridden by the Subtype method, thus explaining the concept of covariant return type in Java.
Example 1: Covariant Return Type Implementation
Let us consider the following example of a car as a covariant type of vehicle. The code depicts the following:
class Vehicle {// use get() method
Vehicle get() {
System.out.println("Vehicle");
return this;
}
}//This class extends the class vehicle
class fourwheels extends Vehicle {
fourwheels get() {
System.out.println("Car");
return this;
}
public static void main(String[] args) {
Vehicle fourwheels = new fourwheels();
fourwheels.get();
}
}
In this code
- A class named vehicle has been created.
- A class named fourwheels is extending the vehicle class.
- The results of the vehicle class have been overridden in the output.
Output
The output has indicated that the class is overridden since the car is printed on the screen.
Therefore, this article sums up the way to handle covariant return types in Java.
Conclusion
The covariant return type in Java deals with non-primitive data types like arrays, lists, and classes. It is useful in Java since it makes the code look cleaner and more usable. The main advantage of this clean code occurs when developing large applications. This article has effectively demonstrated a way to handle the covariant return type in Java.