Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining static methods

Tags:

java

android

This might not have a solution, or I might have not been able to find one, but here it is:

!! Note: the code below is incorrect, I know. I just want to show what exactly I would like to accomplish.

I would like to do something on the lines:

public class ActionBarHandler{

    public static ActionBarHandler withAddOption(){
            //do something ...
        return ActionBarHandler;
    }
    public static ActionBarHandler withEditOption(){
           //do something ...
           return ActionBarHandler;
    }
}

... in order to do the below somewhere in another class (i.e. have it in a single line):

//..
ActionBarHandler.withAddOption().withEditOption().with........;
//..

... instead of doing this:

//..
ActionBarHandler.withAddOption();
ActionBarHandler.withEditOption();
ActionBarHandler.with........;
//..   

Can this be done in any way? With static methods, without having an instance of the class.

like image 982
AndreiBogdan Avatar asked Nov 29 '25 19:11

AndreiBogdan


1 Answers

Yes, declare the method as

public static ActionBarHandler withAddOption(){

and simply return null.

But I don't recommend this. Use objects with method chaining. From a conceptual standpoint, it doesn't make sense to invoke a static method on an instance, even less on a null reference. For that reason alone, you should consider refactoring your design to chain instance method invocations, ie. use objects.

like image 187
Sotirios Delimanolis Avatar answered Dec 02 '25 08:12

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!