Why can't I change the return type of overriden methods (other than covariant return type)?

lyn*_*nxx -1 java overriding jvm

PLEASE NOTE - I am asking WHY? It would be very useful if you could give an example where changing the return type actually breaks the code

why can't I change the return type of an overridden method (other than covariant return types).

class Parent{

   public void sayhello(){ ... };

}

class Child extends Parent{

    public String sayhello() { . . .}

}
Run Code Online (Sandbox Code Playgroud)

Now if I run the following code:

class test{

    public static void main(String[] args){

       Parent p = new Child();
       p.sayHello(); 

        }
    }
Run Code Online (Sandbox Code Playgroud)

Cam someone please confirm if the following steps are happening:

  1. Compiler finds out the type of object 'p' which is Parent.
  2. Compiler checks if method 'sayHello()' is present in Parent class.

  3. During Runtime, JVM finds out that it is a Child object and calls child version of the method.

  4. Child method is called.

Thanks.

Zep*_*hyr 6

Let's use a simple example to explain why it doesn't make any sense to change the return type of an overridden method.

Suppose I have a Car object:

class Car {

    public String getModel() {
        return "Awesome Car";
    }
}
Run Code Online (Sandbox Code Playgroud)

This Car class has a method getModel() that returns a String.

Now, you have another class that extends Car and overrides the getModel() method:

class DumbCar extends Car {
    @Override
    public Hamburger getModel() {
        return new Hamburger();
    }
}
Run Code Online (Sandbox Code Playgroud)

Suddenly, you have a major problem. You create a DumbCar object and since you know that all Car objects can tell you their model, you try to get that model:

DumbCar myCar = new DumbCar();
System.out.println(myCar.getModel());
Run Code Online (Sandbox Code Playgroud)

The output is A juicy Big Mac!

Does that make any sense to you? You cannot drive a Big Mac.


Java is a heavily type-safe language. When you write a statement asking to getModel(), you need to be absolutely, 100% positive, that the data you get back is what you were expecting. Java enforces that expectation.

  • @lynxx-是的。“合同”的想法是绝对正确的。基本上,父类说“除非您承诺提供与我相同的结果类型,否则您不能使用我的方法”。 (3认同)