How to do method chaining in Java? o.m1().m2().m3().m4()

后端 未结 6 822
渐次进展
渐次进展 2020-11-29 02:33

I\'ve seen in many Java code notation that after a method we call another, here is an example.

Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(lay         


        
6条回答
  •  旧巷少年郎
    2020-11-29 03:04

    Adding return this; would surely help in chaining for this class but fail for sub-classes.

    If you want to have the chaining behaviour inherited to the sub-classes also then change your class signature as below:

    Class SuperClass < SubClass extends SuperClass >{}

    This way all sub-classes will inherit method chaining.

    Example:

    public class SuperClass {
    
        public SubClass testMethod(){
            return (SubClass)this;
        }
    
        public static void main(String[] args) {
            SuperClass superClass = new SuperClass();
            superClass.testMethod().testMethod().testMethod();
            System.out.println(superClass.toString());
        }
    
    }
    

提交回复
热议问题