Before JDK 5.0, it was not possible to override a method by changing the return type. When we override a parent class method, the name, argument types and return type of the overriding method in child class has to be exactly same as that of parent class method. Overriding method was said to be invariant with respect to return type.
Covariant return types
Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but child’s return type should be sub-type of parent’s return type. Overriding method becomes variant with respect to return type.
Co-variant return type is based on Liskov substitution principle.
Below is the simple example to understand the co-variant return type with method overriding.
Base fun() Derived fun()
Note : If we swap return types of Base and Derived, then above program would not work. Please see this program for example.
- It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable.
- We get a liberty to have more specific return types when overriding methods.
- Help in preventing run-time ClassCastExceptions on returns
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Two interfaces with same methods having same signature but different return types
- return keyword in Java
- Java System.exit(0) vs C++ return 0
- Java Program to Illustrate a Method Without Parameters and Return Type
- Function overloading and return type
- Return an array of anti-diagonals of given N*N square matrix
- Types of Exception in Java with Examples
- Types of References in Java
- Bounded types with generics in Java
- Comparison of double and float primitive types in Java
- Types of JVM Garbage Collectors in Java with implementation details
- Types of Errors in Java with Examples
- Data types in Java
- How many types of memory areas are allocated by JVM?
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java.Lang.Float class in Java
- Java.io.BufferedInputStream class in Java
- Java.io.ObjectInputStream Class in Java | Set 1
- Java.util.BitSet class in Java with Examples | Set 1
- Java.io.File Class in Java