Covariant Return Type in Java

Object oriented programming (OOP) has a principle named substitutability. In this tutorial, let us learn about substitutability and support for covariant return type in Java. Covariant return type uses the substitutability principle.

Liskov Substitution Principle

Substitutability was introduced by eminent Barbara Liskov and Jeannette Wing. It is also called as Liskov substitution principle.

Let T be a super type and S be its subtype (parent and child class). Then, instances (objects) of T can be substituted with instances of S. Parent’s instances can be replaced with the child’s instances without change in behavior of the program.

WildAnimals

Let WildAnimal be a supertype and Lion be a subtype, then an instance obj1 of WildAnimal can be replaced by an insance obj2 of Lion

.

Covariant, Contravariant and Invariant

The subtyping principle which we discussed above as Liskov principle is called covariant. The reverse of it (instead of child replacing the parent, the reverse of it as parent replacing the child) is called contravariant. If no subtyping is allowed then, it is called invariant.

Covariant Type in Java

From the release of JDK 1.5, covariant types were introduced in Java. Following example source code illustrates the covariant types in java. In the below example, method overriding is used to demonstrate the covariant type.

In class Zoo, the method getWildAnimal returns ‘WildAnimal’ which is a super type. AfricaZoo extends Zoo and overrides the method getWildAnimal. While overriding, the return type of this method is changed from WildAnimal to Lion. This demonstrates covariant type / Liskov substitution principle. We are replacing the supertype’s (WildAnimal) instance with subtype’s (Lion) instance. This was not possible before JDK 1.5 IndiaZoo is just another example which demonstrates the same covariant type.

class WildAnimal {
	public String willYouBite(){
		return "Yes";
	}
}
 
class Lion extends WildAnimal {
	public String whoAreYou() {
		return "Lion";
	}
}

class BengalTiger extends WildAnimal {
	public String whoAreYou() {
		return "Bengal Tiger";
	}
}
 
class Zoo {
     WildAnimal getWildAnimal() {
         return new WildAnimal();
     }
 }
 
class AfricaZoo extends Zoo {
     @Override
     Lion getWildAnimal() {
         return new Lion();
     }
}

class IndiaZoo extends Zoo {
     @Override
     BengalTiger getWildAnimal() {
         return new BengalTiger();
     }
}

public class Covariant {
	public static void main(String args[]){
		AfricaZoo afZoo = new AfricaZoo();
		System.out.println(afZoo.getWildAnimal().whoAreYou());
		IndiaZoo inZoo = new IndiaZoo();
		System.out.println(inZoo.getWildAnimal().whoAreYou());
	}
}

This Core Java tutorial was added on 29/09/2013.

Comments on "Covariant Return Type in Java" Tutorial:

  1. Janusz says:

    Sorry, with Java 7 above example desn’t compile without cast

    AfricaZoo afZoo = new AfricaZoo();
    System.out.println((afZoo.getWildAnimal()).getClass());
    System.out.println(((Lion) afZoo.getWildAnimal()).whoAreYou());

  2. Janusz says:

    AfricaZoo afZoo = new AfricaZoo();
    System.out.println((afZoo.getWildAnimal()).getClass());
    // System.out.println(((Lion) afZoo.getWildAnimal()).whoAreYou());
    Lion lion = (Lion) afZoo.getWildAnimal();
    System.out.println(lion.whoAreYou());

  3. Joe says:

    Janusz,

    No issues, this compiles without any error in JDK 1.7.0_25

    Why do we need a cast here?

  4. Siddu says:

    How annotation works in Java? @Override is an interface how its checks method is overriden propery or not by subclasses?

  5. Siddu says:

    How to de-serilize array of objects? Say I have stored array of employees into a flat file.

  6. Pushkar says:

    Good example for Covariant.

    Kindly give any short example for Contravariant & invariant.

    thanks

  7. Anonymous says:

    Is it possible to you to use contravariant subtyping in java and if yes can you please give some example on it.

    Thanks,
    Sameer.

  8. Joe says:

    Siddu,

    Please refer my tutorial on Java annotations http://javapapers.com/core-java/java-annotations/

  9. Joe says:

    Siddu,

    De-serializing an array is no different.

    To know about serialization please refer http://javapapers.com/core-java/java-serialization/

  10. Joe says:

    Invariant means no support for subtyping. Java does not support contravariant.

  11. Joe says:

    There is no support for contravariant in Java as of now.

  12. Vinuraj M V says:

    Nice and simple as always.. Thank you Joe

  13. Neeraj Kumar says:

    Nice Example. I never thought about this before.

  14. Janusz says:

    Everything OK

    The same code copied and pasted on my personal laptop with true and real Java 7 works fine. Some problems with my remote account in lab temporarily disabled/changed/maintained/whatever the day before beginning of the new academic year

  15. Janusz says:

    What about clear and simple invarian exaple?

  16. Pratik says:

    Good to see you back, hope you are doing well, missed your articles a lot.

    Thanks for posting this article but I don’t get the idea of this article , it’s very simple

  17. Pushkar says:

    Great Thanks a lot now i have clear picture.
    Really nice to see you after long time.

  18. Pushkar says:

    Janusz, declaring as final also the example of invariant.

  19. Pushkar says:

    Hey Joe,

    I have one request once you done with OOP concept.
    We like to read your experience with Threads/multithreading.

  20. Siddu says:

    Thanks, I got it.

  21. Siddu says:

    I understood about annotations. How @Override checks whether method is being overidden properly or not. I mean will it supply any information at runtime.

  22. Joe says:

    Welcome Pushkar.

    I have been working on few things that kept me busy. Those few things are going to be good for javapapers.

    Going forward, you will see lot more articles and interaction than usual.

  23. Joe says:

    Welcome Vinuraj.

  24. Joe says:

    Thanks Pratik, I am doing well. I was focusing on some changes in my personal and career front. Going forward, I can dedicate more time on javapapers :-)

    Yes, this is a simple article. This gives an introduction for a feature in Java 5. Since the audience is in large numbers, I wish to write on mixed depth stuff. Some I want to be in-depth and high complex, some to be of very fundamental and introductory. This is to serve all type of readers.

    So the message is, you have to be selective, but do not go away since there might be some articles coming which will be of interest to you.

    Thanks Pratik.

  25. Joe says:

    Yes Pushkar.

    Threads are pending for a long time and I am really eager to write on it. Sure I will start immediately on Threads.

  26. Pratik says:

    Thanks , will be looking forward for nice articles like all previous ones.

  27. Dhaval says:

    Hi Joe,

    I have read your every post. Its awsome..!
    And today this Gandhiji’s shadow also looking great on javapaper logo. Keep it up and thanks for contribution for java community.

  28. Joe says:

    Thanks Dhaval.

    It is our tribute to the Mahatma.

  29. Ritu Rai says:

    Very nice explanation :)

  30. Seth Williams says:

    Hey Joe, That’s an excellent guide on covariant return type. Thanks a lot for sharing.

  31. […] polymorphism. This is covariant type and the reverse of it is contravariant. We have discussed the substitution principle and covariant types, contravariant and invariant earlier in the linked tutorial. This is demonstrated with a code […]

  32. satya says:

    Hi Joe,
    looking forward to some articles on multithreading.

Comments are closed for this "Covariant Return Type in Java" tutorial.