Skip to content
Advertisement

Method chaining between child and parent classes

So imagine we have the following.

public class Animal {
    public Animal walk(){
        // walk
        return this;
    }
}

public class Dog extends Animal{
    public Dog bark(){
        // bark
        return this;
    }
    public Dog scratch(){
        // scratch
        return this;
    }
}

I’m trying to do this,

Dog dog = new Dog()
    .bark()
    .walk() // error: required Dog but provided Animal, and so it can't find the child method.
    .scratch();

What are the possible ways to achieve this? And what’s the best one (convention)?

Advertisement

Answer

I’ve seen at least two approaches.

  1. Make Animal generic, and use the generic type as return type:
public class Animal<A extends Animal<A>> {
    public A walk(){
        // walk
        return (A) this;
    }
}

public class Dog extends Animal<Dog> {
    public Dog bark(){
        // bark
        return this;
    }
    public Dog scratch(){
        // scratch
        return this;
    }
}
  1. Override the method like Alex R said in his comment.

I prefer option 2, because a) it doesn’t require me to use generics when I want just Animal, and b) it allows me to extend Dog without having to make Dog generic too. With some unit tests using reflection I can check that each method is properly overridden.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement