9

In StringBuilder class I can do like this:

StringBuilder sb = new StringBuilder();
sb.append( "asd").append(34);

method append returns StringBuilder instance, and I can continuosly call that.

My question is it possible to do so in static method context? without class instance

2
  • What do you mean by "In StringBuilder class"- you can't edit the class Commented Dec 18, 2010 at 11:58
  • By static context do you mean to do somthing like StringBuilder.append()? If it is why would you want to do it? Commented Dec 18, 2010 at 12:02

5 Answers 5

15

Yes. Like this (untested).

public class Static {

  private final static Static INSTANCE = new Static();

  public static Static doStuff(...) {
     ...;
     return INSTANCE;
  }

  public static Static doOtherStuff() {
    ....
    return INSTANCE;
  }
}

You can now have code like.

Static.doStuff(...).doOtherStuff(...).doStuff(...);

I would recommend against it though.

Sign up to request clarification or add additional context in comments.

2 Comments

INSTANCE has to be static in this case.
@GuisongHe Care to explain?
5

This is called method-chaining.

To do it, you always need an instantiated object. So, sorry, but you cannot do it in a static context as there is no object associated with that.

1 Comment

This isn't true. I'm ashamed of this community that no one noticed it and commented in 11 years.
2

Do you want this ?

public class AppendOperation() {
    private static StringBuilder sb =  new StringBuilder(); 

    public static StringBuilder append(String s){
        return sb.append(s);
    }

    public static void main(String... args){

         System.out.println(AppendOperation.append("ada").append("dsa").append("asd"));

    }

}

maybe I don't understand the question (static context) correctly

do you mean this?

static {

} //of course you can do this, too

if not all above, you can't do without any static method because append() is not static

Comments

1

You want the builder pattern on a static? No. Best to convert your statics to instances.

Comments

1

As said here You can simply return null. For example:

public class MyClass {

    public static MyClass myMethod() {
        doSomething();
        return null;
    }
}

1 Comment

It's strange to return null . You expect it to throw a NPE, but it actually works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.