OOP in Java: Class inheritance with method chaining

前端 未结 4 738
旧巷少年郎
旧巷少年郎 2020-12-16 13:54

I have a parent class, which defines a collection of chainer methods (methods that return \"this\"). I want to define multiple child classes that contain their own chainer

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 13:59

    You can just cast it.

    ChainChild child = new ChainChild();
    ((ChainChild) child.foo()).bar();
    

    You could try:

    public ? extends Chain foo() {
        return this;
    }
    

    But I'm not sure that will help, even if it compiles.

提交回复
热议问题