Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading