What is co-variant return type in java?

What is co-variant return type in java?

A co-variant return type allows to override a super class method that returns a type that sub class type of super class method’s return type. It is to minimize up casting and down casting.

The following code snippet depicts the concept:
class Parent
{
    Parent sampleMethod()
    {
        System.out.println(“Parent sampleMethod() invoked”);
        return this;
    }
}

class Child extends Parent
{
    Child sampleMethod()
    {
        System.out.println(“Child sampleMethod() invoked”);
        return this;
    }
}

class Covariant
{
    public static void main(String args[])
    {
        Child child1 = new Child();
        Child child2 = new child1.sampleMethod();
        Parent parent1 = child1.sampleMethod();
    }
}
Define collable collections in java
A callable collection is an interface whose implementers define a single method with no arguments. The Callable interface resembles Runnable..
Purpose of making a method thread safe - Java
Java supports threads natively without using additional libraries. Using ‘synchronized’ key word makes the methods thread safe.......
Can you explain why a constructor doesn't have return type? - Java
The primary goal of a constructor is to create an object. Though the constructor resembles a method, its explicit purpose is to initialize the instance variables.....
Post your comment