In Java, polymorphism allows method to be overridden in subclass with different implementation. However, when overriding methods, the return type of the method must usually match exactly. This is where Covariant Return Type comes into play.
What is Covariant Return Type?
The covariant return type specifies that the return type of overridden method in subclass may vary in the same direction as the subclass. In simple terms, if the superclass method returns a type A
, then the overridden method in the subclass can return B
(where B
is a subclass of A
).
This feature was introduced in Java 5 and helps make code cleaner, safer, and more readable.
Example of Covariant Return Type in Java
class A {
A get() {
return this;
}
}
class B1 extends A {
@Override
B1 get() { // Return type changed to subclass type
return this;
}
void message() {
System.out.println("Welcome to covariant return type");
}
public static void main(String args[]) {
new B1().get().message();
}
}
Output
Welcome to covariant return type
Explanation
- In the above example:
- The
get()
method in class A returns an object of typeA
. - The
get()
method in subclass B1 overrides this method but changes the return type toB1
.
- The
- This is valid because
B1
is-aA
(inheritance). - Both methods are considered overridden, even though they return different types. This behavior is called Covariant Return Type.
Why is Covariant Return Type Useful?
Before covariant return types, we had to perform explicit type casting to access subclass-specific methods after overriding.
With covariant return types:
- Avoids confusing type casts in class hierarchies.
- Makes the code more readable and maintainable.
- In method overriding, it provides the liberty to return more specific types.
-
Prevents
ClassCastException
at runtime when handling returned objects.
Key Advantages
- Code becomes cleaner and easier to understand.
- Reduces boilerplate and explicit type casting.
- Improves type safety at compile time.
Top comments (0)