Jump to content

Covariant return type

From Wikipedia, the free encyclopedia

In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" (derived) type when the method is overridden in a subclass. A notable language in which this is a fairly common paradigm is C++.

C# supports return type covariance as of version 9.0.[1] Covariant return types have been (partially) allowed in the Java language since the release of JDK5.0,[2] so the following example wouldn't compile on a previous release:

// Classes used as return types:

class A {
}

class B extends A {
}

// "Class B is narrower than class A"
// Classes demonstrating method overriding:

class C {
    A getFoo() {
        return new A();
    }
}

class D extends C {
    // Overriding getFoo() in parent class C
    B getFoo() {
        return new B();
    }
}

More specifically, covariant (wide to narrower) or contravariant (narrow to wider) return type refers to a situation where the return type of the overriding method is changed to a type related to (but different from) the return type of the original overridden method. The relationship between the two covariant return types is usually one which allows substitution of the one type with the other, following the Liskov substitution principle. This usually implies that the return types of the overriding methods will be subtypes of the return type of the overridden method. The above example specifically illustrates such a case. If substitution is not allowed, the return type is invariant and causes a compile error.

Another example of covariance with the help of built in Object and String class of Java:

class Parent {
    public Object getFoo() {
        return null;
    }
}

class Child extends Parent {
    // String is child of the greater Object class
    public String getFoo() {
        return "This is a string";
    }

    // Driver code
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println(child.getFoo());
    }
}

See also

[edit]
[edit]

References

[edit]
  1. ^ "Covariant Returns". Microsoft Docs. Retrieved 8 September 2021.
  2. ^ bridge Methods were introduced to circumvent problems introduced by polymorphism and the new generic type erasure