OOP in Java: Class inheritance with method chaining

前端 未结 4 732
旧巷少年郎
旧巷少年郎 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 14:18

    Here's an improvement on OldCurmudgeon's method:

    public class Parent> {
    
        @SuppressWarnings("unchecked")
        private final This THIS = (This)this;
    
        public This foo() {
            //...
            return THIS;
        }
    
        public This bar() {
            //...
            return THIS;
        }    
    }
    
    public class Child extends Parent {
    
        // you can override super with covariant return type
        @Override
        public Child bar() {
            super.bar();
    
            return this;
        }
    }
    
    
    Child child = 
    new Child()
    .foo()
    .bar();
    

    The improvement is making an unchecked cast only once and save it to a constant THIS, which you can reuse as the return value for method chaining.

    This removes unchecked casts in every method and makes the code clearer.

    You can override Parent's methods by returning Child instead of This (covariant return type).

提交回复
热议问题