This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread 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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 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: 386
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: 2956
    
  12

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: 3742
    
  16
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??
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: please explain this syntax
 
It's not a secret anymore!