I’ve got a question about return types in inherited methods in Java. I’ve got a class and an inherited class. In the inherited class, there’s a specific method. It also inherits a method from the parent class that returns instance of itself.
I want something like this class hierarchy:
public class Foo {
public Foo bar()
{
return this;
}
}
public class FooInherited extends Foo {
public Whatever baz()
{
return new Whatever();
}
}
My question is if I can call the inherited method from its instance and then call the specific method without overriding the method to return the inherited class or casting the classes explicitly.
Now I want to have a code fragment like this :
FooInherited foo = new FooInherited();
Whatever w = foo.bar().baz();
I feel a difficulty in this, but I’m not very sure if Java has any time saving mechanism for programmers in such situations.
Unless you override the method in the subclass you will have to cast:
However, due to covariant return types in java you can override it like this:
After overriding you no longer have to cast because the static type of foo is
FooInherited: