Covariant return type in Java

[2919 views]




Covariant return type is a feature introduced in Java 5 that allows a subclass method to return a more specific type than the type returned by the overridden superclass method. In other words, the return type of an overridden method in a subclass can be a subtype of the return type of the original method in the superclass.

Here's an example to illustrate this concept:

class Animal { public Animal getAnimal() { return new Animal(); } } class Dog extends Animal { @Override public Dog getAnimal() { return new Dog(); } }
```

In the above example, the `Dog` class overrides the `getAnimal()` method of its superclass `Animal`. The return type of the overridden method in the `Dog` class is `Dog`, which is a subclass of `Animal`. This is allowed because `Dog` is more specific than `Animal`.

Covariant return types are useful when working with polymorphism, especially when dealing with class hierarchies and inheritance. They allow you to write more concise and expressive code by eliminating the need for type casting in certain situations.

                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?



Comments










Best Search Engine:

Sponsored Deals ends in



Thinking of Buying Products Online??

Use Below Search to get Best Discounts Online

Interesting Technical Quizzes:

Online Browser Games:
     



Search Tags