KaliMa KaliMa - 10 months ago 38
Java Question

How to get a subclass to override a parent abstract method with an extended type?

For example

public abstract class ParentClass {

public abstract FooType getFoo();

and then something like

public abstract class SomeClass extends ParentClass {

public abstract SpecialFooType getFoo(); //clashes with the parent!

In this case the getFoo() from SomeClass is supposed to be a FooType that implements the interface SpecialFooType. However I don't know how to set up the syntax for this.

Answer Source

Inheritance is more than just putting extends on some class declaration.

For example, your classes have to follow the Liskov substitution principle. And that principle gives rules how overridding of methods has to look like.

It actually allows to narrow the type of return values; like: the base class has Number getFoo(); and the subclass can do Integer getFoo(). But in your case, the return types are different; therefore your idea is simply wrong on an conceptual level!

The reasoning behind that. If you have client code that invokes that method, the client must not need to know if it is calling that method on the base class ... or some subclass. In other words: the client code must be able to deal with a Number response, so of course, it will be able to deal with an Integer coming back. Now consider how that should work in your setup ... as said: it wouldn't!