Objectname.methodone()
.methodtwo()
.methodthree()
.methodfour();
Are these statements above same as
Objectname.methodone();
Objectname.methodtwo();
Objectname.methodthree();
Objectname.methodfour();
Thanks,
Objectname.methodone()
.methodtwo()
.methodthree()
.methodfour();
Are these statements above same as
Objectname.methodone();
Objectname.methodtwo();
Objectname.methodthree();
Objectname.methodfour();
Thanks,
It depends on the return types of methodone
, methodtwo
, methodthree
and methodfour
. What's going on is you're calling methodone
on Objectname
, methodtwo
on the return type of methodone
and so on.
If methodone
through methodfour
all return this
, then yes, it would be the same.
This is referred to as method chaining.
Probably, if the implementation of each of those methods ends with return this;
so that the calls can be chained like that. But it's possible that each returns a reference to a different object, on which the "next" method is then called.
no its not like that it is as
Objectname.methodone().methodtwo().methodthree().methodfour();
similar to the
result = method1().method2(). ........ method n()
its called method chaining
refer Method chaining in Java
EXAMPLE
class Person
{
private final String name;
private int age;
public Person setName(final String name) {
this.name = name;
return this;
}
public Person setAge(final int AGE) {
this.age = AGE;
return this;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
Person person = new Person();
// Output of this sequence will be: Hello, my name is Peter and I am 21 years old.
person.setName("Peter").setAge(21).introduce();
}
}
Not necessarily, methodtwo
is called on the return value of methodone
and methodthree
is called on the return value of methodtwo
and so on. They are not (necessarily) called on the same object.
The equivalent is:
MethodOneReturnType x = object.methodone();
MethodTwoReturnType y = x.methodtwo();
MethodThreeReturnType z = y.methodthree();
It depends on what those methods return. methodtwo is being called on the return of methodone. if methodone returns Objectname, then they are the same.
it is very unlikely they'll be same. Think of a pizza builder.
new PizzaBuilder().withDough("dough").withSauce("sauce").withTopping("topping").build();
this builds the complete pizza. whereas if you call the with methods separately it will build only a partial pizza.