- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are covariant return types in Java?
In general, in overriding, the method in a superclass and subclass have the same name and, parameters. But, when it comes to returning type, the method in the subclass can return the subtype of the return type of the method in the superclass.
Example
If you observe the following example super class has a method named demoMethod() and it returns a value of the type list. If we override this method the method in the subclass can return a value of the type List (which is in the superclass) or, it can also return the subtype of the List (return type of the method in the super class) such as ArrayList, Stack, Vector etc.
In this scenario the sub class method returns an ArrayList, subtype of the return type of the super class i.e. List. This sub type (ArrayList) is known as covariant type.
Example
class Test{ int data =100; Test demoMethod(){ return this; } } public class Sample extends Test{ int data = 1000; Sample demoMethod(){ return this; } public static void main(String args[]){ Sample sam = new Sample(); System.out.println(sam.demoMethod().data); } }
Output
1000
- Related Articles
- Covariant return types in Java
- Covariant return types in Java programming.
- What is covariant return type in Java?
- Covariant return type in Java
- What are primitive data types in Java?
- What are reference data types in Java?
- What are raw types in generics in Java?
- What are the types of arrays in Java?
- What are the different types of classes in Java?
- What are the different types of keywords in Java?
- What are the different module types in Java 9?
- What are the various return types of a controller action in C# ASP.NET WebAPI?
- What are the different types of JOptionPane dialogs in Java?
- What are the different types of nested classes are defined in Java?
- What are the different "/types" commands in JShell in Java 9?
