Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a chained method

Tags:

java

Let's have class A with a method useful for chaining:

class A {
  A foo() {
    // do stuff
    return this;
  }
}

You could now do a.foo().foo().foo() (think: builder pattern). Let class B extend it:

class B extends A {
}

B b;

Now invoking b.foo() returns actual type B, but declared A. Therefore I cannot write:

B other = b.foo();

I would have to write either:

B other = (B) b.foo();

Or override foo() in B:

class B extends A {
  @Override
  B foo() {
    super.foo();
    return this;
  }
}

Is there a nice way to do this?

like image 650
vektor Avatar asked Jul 23 '26 13:07

vektor


1 Answers

Did this by implementing an additional generic method as(type) to the superclass. This helps to have a nicer cast for fluent interfaces.

class A {
    public A foo() {
        return this;
    }
    @SuppressWarnings("unchecked")
    public <T extends A> T as(Class<T> clazz) {
        return (T) this;
    }
}

class B extends A  {}

So you can write a.foo().as(B.class).methodOfB(..). And you do not need to reimplement foo() in all subclasses.

like image 149
Cfx Avatar answered Jul 26 '26 02:07

Cfx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!