AnswerBun.com

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

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?

Stack Overflow Asked by Stefan on December 29, 2020

1 Answers

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!

Related Questions

Flight destination check programm – C++

3  Asked on January 12, 2021 by mrfreeman16

   

How to execute (./myscript) inside awk or bash script?

3  Asked on January 12, 2021 by redouane-nouh

   

Disable nuxt link based on boolean

3  Asked on January 12, 2021 by samantha

     

Android Preventing Double Click On A Layout with handher

1  Asked on January 12, 2021 by user13380366

     

How to center align the label text inside the option tag?

1  Asked on January 11, 2021 by mr-spock

         

How can I read the CSS for mobile images

0  Asked on January 11, 2021 by power-rico

   

Deleting from array using unset creates values

2  Asked on January 11, 2021 by cameron

 

passport.socket.io cant fix no session found

2  Asked on January 11, 2021 by edi_hadzic

         

Output should look like a quotation

4  Asked on January 11, 2021 by maurya

   

Sorting DateTime column in ASP.NET MVC

2  Asked on January 11, 2021 by steven85791

     

Rounding does not match all expected results

1  Asked on January 11, 2021 by aa-44

   

Django tabular input form (user can key in data into table)

1  Asked on January 11, 2021 by eka-buyung-lienadi

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.