OOP in Java: Class inheritance with method chaining

前端 未结 4 739
旧巷少年郎
旧巷少年郎 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:00

    I've written this sample using generics based on your needs.

    class Parent {
        public  T foo() {
            return (T)this;
        }
    }
    
    class Child extends Parent {
    
    }
    
    class AnotherChild extends Parent {
    
    }
    
    public class Test {
        public static void main(String[] args) {
    
            Parent p = new Child();
            System.out.println(p);
            Child c = p.foo();
            System.out.println(c);
            //throws ClassCastException here since Child is not AnotherChild
            AnotherChild ac = p.foo();
            System.out.println(ac);
        }
    }
    

提交回复
热议问题