Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!.POSTED!not-for-mail From: Novice Newsgroups: comp.lang.java.programmer Subject: Re: Question about Effective Java Date: Fri, 10 Feb 2012 00:40:44 +0000 (UTC) Organization: Your Company Lines: 48 Message-ID: References: NNTP-Posting-Host: /kSec8Zpu/mSG50nCPQbWQ.user.speranza.aioe.org X-Complaints-To: abuse@aioe.org User-Agent: Xnews/5.04.25 X-Antivirus-Status: Clean X-Notice: Filtered by postfilter v. 0.8.2 X-Antivirus: avast! (VPS 120209-3, 2012-02-09), Outbound message Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:11896 Patricia Shanahan wrote in news:QrudnRBcJtTn26nSnZ2dnUVZ_qSdnZ2d@earthlink.com: > On 2/9/2012 9:54 AM, Novice wrote: >> I'm trying to understand the example on page 14 of Effective Java by >> Joshua Bloch (Second Edition). I hope someone here can help. > ... >> public Builder sodium(int val) { >> this.sodium = val; >> return this; >> } > ...: >> 1. I understand that a NutritionFacts could conceivably be just a >> servingSize and a number of servings. All of the other values are >> optional on an individual basis: any one or more of them could be >> there but don't need to be. Any value that is omitted takes a default >> (of zero in this example). But why are the methods calories(), fat(), >> carbohydrate() and sodium() each returning Builder? They aren't >> constructors and they only deal with one data value, fat or calories >> or whatever, but they apparently return a complete Builder. >> > > Don't think in terms of "return a complete Builder". Java programs do > not, and cannot, pass objects around as method arguments or results. > sodium really returns a Builder reference. A reference can either be > null or be a pointer to an object of appropriate class. > > Inside sodium, "this" is a pointer to the current object. Returning it > allows chaining of several method calls. > I'll have to mull that over for a bit and consider the implications. At first glance it seems simple enough; in any other class, "this" refers to an instance of the class that contains the "this", just like we see here. But I'm not used to seeing several methods in a class all return "this". I'm also not used to named classes nested within classes. (I'm familiar with anonymous inner classes like window listeners and with putting additional named classes within the same source file in a sequential fashion but putting a named class within another is still feels a little odd.) I'll post back if I can't make my peace with this slightly exotic technique ;-) Thanks for your help. -- Novice