Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialP M
7,320 PointsWhy the ParseUser class methods cannot be chained?
You show an example with method chaining on the AlertView.Builder class, but when I tried to chain the methods on the ParseUser object, i.e. newUser.setUsername(username).setPassword(password)
, it doesn't work. What's the difference? What methods in Java can be chained and which ones cannot?
1 Answer
Gunjeet Hattar
14,483 PointsYou can only method chain in Java if the multiple methods in the chain are invoked on the same object in a single statement. By convention every chained method will return a reference to this (the current object). If it doesn't, then you cannot method chain it.
It's like igniting the very first method, which returns a reference to this, the latter then sets off the next method and so on. In short the output from the previous is used as input for the next method (all this)
So lets consider AlertDialogue.Builder. The default constructor when creating a new AlertDialogue.Builder object is AlertDialog.Builder(Context context)
Pay attention to context which refers to the current caller of this object, in our case the MainActivity. So once this statement executes it will return a reference to this or current object. He then uses the method setTitle which is defined as
public AlertDialog.Builder setTitle (CharSequence title) **
And what does this method return
**This Builder object to allow for chaining of calls to set methods
So it again returns a reference to the current object.
Similar case for the next chained methods. This is why we could easily chain them
Now lets consider ParseUser. Refer declaration here
When creating a new pareUser the default constructor is declared as ParseUser()
clearly there is no reference to the current object and nothing is returned. So any method that this ParseUser object calls has to be defined separately and cannot be chained since a method for e.g. setUsername will have no clue which object is it referencing to. Thus we use the object name to call it separately.
Method chaining is quite a twisted topic. Took me a while before I could get an understanding. I hope all of it makes sense.
P M
7,320 PointsP M
7,320 PointsAwesome answer, all I needed to know at this point and even more. Thanks a lot!