• Post Reply Bookmark Topic Watch Topic
  • New Topic

How can i interpret this..  RSS feed

 
nirmal Rchavan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringBuffer sb = new StringBuffer("My Name is");
sb.append(" slim shady").reverse(); // ---line 2
System.out.println(sb);
OUTPUT: My Name is slim shady

My question is in regards to line 2, Object.method().method();
1) How do i interpret line2

when i do it with a class that i created (with 2 methods) ie
when i say
MyClass mc = new MyClass();
mc.method1().mehtod2(); //compiler error
//Cannot invoke method2(int) on the
//primitive type int
2) why is it not possible with my class

Thanks for your time
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the StringBuffer.append javadoc. There you will see that the append method returns the StringBuffer itself.
The second method is called on the object the first method returns, which is the StringBuffer itself.
If your own first method returns something else or nothing at all, you will get a compilation error.

This type of interface is sometimes called a Fluent interface
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is possible because most of the StringBuffer methods return the StringBuffer object itself.

Basically, your code is short for:

The chaining is something that can be found some more, e.g. in ProcessBuilder. It just makes it easier for you, but you can just choose to not use it if you like.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW: My output is "ydahs mils si emaN yM" which is what we'd expect after all the other conversation, no?
 
nirmal Rchavan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.
and Yes sir the output should be the reverse string(which i mis-typed), and the chaining process is really great!...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!