Igazi
Igazi

Reputation: 43

How to use a method append(String) onto itself in Java?

What I am trying to do is use method().method() in the following code:

public class Practice {
    public static void main(String[] args){
        Message m = new Message("test");
        m.append("in").append("progress").append("...");
        m.printMessage();
    }
}

My class Message is this:

public class Message {

    private String astring;

    public void append(String test) {
        astring += test;
    }

    public Message(String astring) {
        this.astring = astring;

    }
    public void printMessage() {
        System.out.println(astring);
    }
}

How can I use .append().append()?

Upvotes: 4

Views: 1947

Answers (2)

synchronizer
synchronizer

Reputation: 2075

Change

public void append(String test) {
    astring += test;
}

into

public Message append(String test) {
    astring += test;
    return this;
}

In effect, each append() will return a pointer to the relevant Message object, allowing you to apply append() to that Message repeatedly in a chain. I would use an internal char array to avoid O(N^2) String concatenation though. Alternately, append to an internal StringBuilder delegate object, whose append() method allows for the chained calls.

Upvotes: 3

Jacob G.
Jacob G.

Reputation: 29730

Change the method to the following:

public Message append(String test) {
    astring += test;
    return this;
}

Upvotes: 4

Related Questions