Covariant Return type in JAVA

Priyanshichaki
2 min readMay 17, 2020

--

Covariant return type in JAVA (Function Overriding)
Covariant return type in JAVA (Method Overriding)

Covariant return type in JAVA expects that the overriding function in sub-class can have different return data type and not the same return type as that of parent class function, provided that the return type of the overriding function in the sub-class is a sub-type of Parent’s return type.

Here is a support code for better understanding of how Covariant return type works in JAVA-

class Marks

{

}

class SubjectMarks extends Marks

{

}

class Departments{

public Marks getMarks(){

System.out.println(“getMarks() function from Departments class”);

return new Marks();

}

}

class Students extends Departments

{

@Override

public Marks getMarks()

{

System.out.println(“getMarks() function from Students class”);

return new SubjectMarks();

}

}

public class Testt //file name Testt.java {

public static void main(String args[])

{

Departments dept= new Departments();

dept.getMarks();

Students stud= new Students();

stud.getMarks();

} }

Output:

getMarks() function from Departments class

getMarks() function from Students class

Explanation:

Two classes Marks class and SubjectMarks class are created to generate return types of these respective class types, or in other words to create a return type of Marks (class) type and another return type of SubjectMarks (class) type.

Note here, that Marks (class) is the parent class and SubjectMarks (class) is a child class of Marks (class).

Covariant return type expects that the overriding function in sub-class can have different return data type and not the same return type as that of parent class function, provided that the return type of the overriding function in the sub-class is a subtype of Parent’s return type.

Going further with this example, there are two classes Department (class) and Student (class), where Student class is a child of Department class. The overridden function getMarks() present in Parent class i.e. Department class has return type of Marks (class) type. The overriding function getMarks() in the Student class which is a child of Department class return type of SubjectMarks (class) type. This SubjectMarks (class) is a child of Marks (class) so the overriding function present in the child class here in this example Student (class) can have a return type which is a sub-type of parent’s return type and here SubjectMarks is a sub-type of Marks.

--

--