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:
Compiler checks if method 'sayHello()' is present in Parent class.
During Runtime, JVM finds out that it is a Child object and calls child version of the method.
Thanks.
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.
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |