Tom Fobear
Tom Fobear

Reputation: 6749

Java, invoking methods on objects one after the other (C# style)

I was wondering if Java had a form of this:

new Object().methodOne("This is the first method").methodTwo("Second attached method");
new String("Hello World  ").TrimEnd().Split(' ');

thank you

Upvotes: 1

Views: 130

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 994767

Yes, you can do this sort of thing in Java. For example:

class Test {
    public Test method(int x) {
        return this;
    }
    public Test method2(String y) {
        return this;
    }
}

Then, you can:

new Test().method(5).method2("test");

This kind of interface where you can string method calls together is called a fluent interface. Martin Fowler (who coined the term) actually first demonstrated it using Java.

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351748

You can do this in Java. It depends on the return type of the method.

A particular API may not support this in that methods may not return types that are easily used like this. But Java most certainly supports accessing instance members of objects without assigning them to a variable.

I think what you might be after is the concept of a fluent interface (which can be expressed with Java, of course).

Upvotes: 5

Related Questions