This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes please explain this syntax Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please explain this syntax" Watch "please explain this syntax" New topic
Author

please explain this syntax

nirjari patel
Ranch Hand

Joined: Apr 23, 2009
Posts: 371
doc.addElement("data").addElement("something")

How does this syntax work ?
Does it add "data" and "something" both ?
Does it not need to be added separately ?
If we can ad teo elements in one statement, then can we add three elements in one statement ?

thanks

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

what is the doc ?
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2849
    
  11

Whatever "doc" may be, the addElement() method returns "this", that is a reference to the doc object itself. Why? To enable the kind of syntax you posted here, which can, at times, be convenient. It's called the Method Chaining pattern.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3477
    
  13
Greg Charles wrote:Whatever "doc" may be, the addElement() method returns "this", that is a reference to the doc object itself.


Not necessarily. addElement could return an instance of any class that has an addElement(String) method.
Without knowing the type of 'doc', you can't say what addElement returns.
cchetan jain
Ranch Hand

Joined: Jul 05, 2009
Posts: 30
firstly doc is in object.after applying the method addElement() on it .it returns an object(may be it is object of the type of doc)..on which by chaining rule again the addElement()method is applied..and now it adds 'something' to it..clear or not??
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: please explain this syntax