OOP in Java: Class inheritance with method chaining

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

    A method in the parent class that returns this will still return a reference to the object of the child class. You will only be able to treat it as an object of the parent class (unless you cast it) but it will actually be of its original type.

    You could consider using generics like this:

    // This seems a bit too contrived for my liking. Perhaps someone else will have a better idea.
    public class Parent> {
        T foo () {
            return (T) this;
        }
    }
    
    public class Child extends Parent {
        public void bar () {
            Child c = foo();
        }
    }
    

提交回复
热议问题