I was going through inheritance rules. I came across below rule
return type of overriding method can be child class of return type declared in overridden method.
I don't understand the purpose behind it. If any one can explain it.
It allows you to use more specific return type when you're using specific subclass. A common example would be to use more specific return type when overriding clone()
method. It's declared like
protected native Object clone() throws CloneNotSupportedException;
So it returns Object
. But in your particular class (say, MyObject
) you can redefine clone like this:
public MyObject clone() {
try {
return (MyObject)super.clone();
}
catch(CloneNotSupportedException ex) {
throw new InternalError();
}
}
This way users of your MyObject
class can call the clone()
method and get the MyObject
result without additional casting. It's quite convenient.
Okay, so here's what I think can happen.
Let's say you have the following:
public class Animal {
...
public Animal anotherAnimal() {
return new Animal();
}
}
public class Dog extends Animal {
...
public Dog anotherAnimal() {
return new Dog();
}
}
So what's happening here is we're overriding the superclass method anotherAnimal
, and the rule is that in the child class (Dog), we are allowed to return a different object than the superclass' method did, but it has to return an object that's a subclass.
In other words, because Dog
is a subclass of Animal
we're able to return it in the overridden Dog
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.