class One {
public One foo() { return this; }
}
class Two extends One {
public One foo() { return this; }
}
class Three extends Two {
public Object foo() { return this; }
}
public Object foo() { return this; }
throws a compilation error. Why is that? Can someone explain why "Object" type is not possible? Is Object the base class of Class One, Two? If So why does it throws an error?
Please change the title of the question as I couldnt find a suitable title.
Three.foo
is trying to override Two.foo()
, but it doesn't do it properly. Suppose I were to write:
One f = new Three();
One other = f.foo();
Ignoring the fact that actually Three.foo()
does return a One
, the signature of Three.foo()
doesn't guarantee it. Therefore it's not an appropriate override for a method which does have to return a One
.
Note that you can change the return type and still override, but it has to be more specific rather than less. In other words, this would be okay:
class Three extends Two {
public Three foo() { return this; }
}
because Three
is more specific than One
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With