TransWikia.com

Covariant data types: Why return type must be same as or child of its 'parent method' return type?

Stack Overflow Asked by Stefan on December 29, 2020

As this is not so famous concept, I will make a little intro.

Covariant return type of a method is one that can be replaced by a
"narrower" type when the method is overridden in a subclass.

So I can compile just fine this little program (as String is child of Object):

public class House {
    Object someMethod(){
        return null;
    }
}

class DogHouse extends House{
    @Override
    String someMethod() {
        return null;
    }
}

The rule is easy enough to remember, but I don’t understand it. My question is this:

Why can the return type in someMethod in DogHouse only be the same or child of return type in someMethod in class House? I hope the question is quite clear.

Or..(for example) why this code wouldn’t compile if I had put return type in someMethod in class House Integer for example? (String is not a child of Integer)

What is happening ‘behind the scenes’ so I can understand it?

One Answer

The way to understand this is to think of the subclass as a specific type of the parent class. This means it still needs to adhere to the behavior defined by the parent. The parent class defines a someMethod method that returns an Object. Subclasses can't break this behavior, but they can further specify it - a DogHouse's someMethod still returns an Object, it just happens to be a String.

Correct answer by Mureinik on December 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP