Need explanation on this Java object initialization syntax

136 Views Asked by At

I'm a C\C++ programmer just starting on Java.

I came across this working Java snippet syntax that I understand what it does but I can't understand the logic of the syntax.

object x = new object
            .SetContent(aaa)
            .SetIcon(bbb)
            .SetText(ccc);

I get that the equivalent C++ code is:

object* x = new object;

x->SetContent(aaa);
x->SetIcon(bbb);
x->SetText(ccc);

Can anyone explain to me the logic in the Java syntax?
Is this something like the Visual Basic's With Statement?

P.S. Don't think it matters but the Java snippet is from an Android program.

5

There are 5 best solutions below

0
On

This is method chaining in java, where each method returns the current instance so that you can invoke the next method on current returned object from that method.

0
On

Those chain calls are possible because each setter method returns a reference to this:

public object SetContent(final String input){
    this.aaa = input;
    return this;
}
0
On

It's method chaining, where each method invocation returns the object it was invoked on. It's very common to see in Java when creating an object with a Builder, e.g.

Foo foo = FooBuilder.builder()
    .setBar("bar")
    .setVolume(11)
    .setAnswer(42)
    .build();

Where each .set___() method returns the updated builder object, and the final build() call returns the actual Foo instance. It would be perfectly equivalent to do this:

FooBuilder builder = FooBuilder.builder();
builder = builder.setBar("bar");
builder = builder.setVolume(11);
builder = builder.setAnswer(42);
Foo foo = builder.build();

But IMO the first version is much more readable. I'm not much of a C++ guy but I think you can do the same thing there.

EDIT: Here's a real life example: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableSet.Builder.html

0
On

This syntax is creating the 'x' object, you should know that objects are references in Java. this syntax is equivalent to:

private object x = new object();
x.setContent(aaa);
x.setIcon(bbb);
x.setText(ccc);

so first it create the object and then it calls each method.

0
On

The instance of that Object is returned by each of the methods called,the next subsequent method uses that returned instance to operate further. This is internally done by returning this .

Example:

Object methodFirst(Object ob1)
{
ob1.doSomeOperations();
return this;
}

Object methodSecond(Object ob1)
{
ob1.doSomeOtherOperations();
return this;
}

the above methods can be called like :

Object newObject = oldObject.methodFirst().methodSecond(); 

A more comprehensive and deep explanation can be found here