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

Time:04-28

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!*

CodePudding user response:

When I try your code the instance returned is indeed Child :

public static void main(String[] args) {
        
    Child child = new Child();
    System.out.println(child.getClass());
    System.out.println(child.doSth());
}

So there seems to be a problem with your code. Please post the entire code.

CodePudding user response:

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.
  • Related