Skip to content
Advertisement

Java 8: Child should inherit methods from parent but return itself (FluentApi)

I want to do Inheritance with the concept of fluent api. So the parent Class is defining its methods and return itself (this). The child should be able to use this methods but return not the parent but its own class instance!

How can I achieve this? I want to instantiate the parent, so abstract is not a option.

public class Parent {
    
    // fields, constructor a.s.o
    public Parent doSth() {
        //doSth
        return this;
    }
}

public class Child extends Parent{
    
    // fields, constructor a.s.o
}

If I execute now..

new Child().doSth() => *is returning Parent, not Child!*

Advertisement

Answer

We need to acknowledge the conflict between abstraction and inheritance in this case, at least in limited aspects. Solving for it (assuming you’re willing to sacrifice programming to the interface for your callers) will depend on a few things:

  • Parent.doSth() does not instantiate a new Parent() and returning it (your code doesn’t seem to) – or you’d be making room for runtime errors
  • You’re willing to override the method just for the sake of carrying the specific type in chained calls. This, of course, will apply to all relevant methods.

If both of those have a yes:

class Child extends Parent{
     @Override
    public Child doSth() {
         super.doSth();
        return this;
    }
}

It’s important to note that doing this raises a lot of questions, among which:

  • If this Parent/Child relationship should mean nothing to your callers, then you should also ask yourself why Child is extending Parent at all. If you don’t have a good reason, then use composition rather than inheritance. This code is depriving both you and your callers of one key feature of OOP (polymorphism, in the sense of the Parent type being held by objects of various sub-classes)
  • Overriding the method (for a reason that isn’t very sound, in terms of principles) may be construed as creating a maintenance burden without solid justification.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement