Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #11885

Re: Question about Effective Java

Date 2012-02-09 14:19 -0800
From Patricia Shanahan <pats@acm.org>
Newsgroups comp.lang.java.programmer
Subject Re: Question about Effective Java
References <Xns9FF4833D32E5Ajpnasty@94.75.214.39>
Message-ID <QrudnRBcJtTn26nSnZ2dnUVZ_qSdnZ2d@earthlink.com> (permalink)

Show all headers | View raw


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.

Patricia

Back to comp.lang.java.programmer | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Question about Effective Java Novice <novice@example..com> - 2012-02-09 17:54 +0000
  Re: Question about Effective Java markspace <-@.> - 2012-02-09 10:39 -0800
    Re: Question about Effective Java Novice <novice@example..com> - 2012-02-10 00:07 +0000
      Re: Question about Effective Java markspace <-@.> - 2012-02-09 16:42 -0800
  Re: Question about Effective Java Patricia Shanahan <pats@acm.org> - 2012-02-09 14:19 -0800
    Re: Question about Effective Java Novice <novice@example..com> - 2012-02-10 00:40 +0000
      Re: Question about Effective Java Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-02-09 21:08 -0500
        Re: Question about Effective Java Lew <lewbloch@gmail.com> - 2012-02-10 09:01 -0800
  Re: Question about Effective Java "John B. Matthews" <nospam@nospam.invalid> - 2012-02-10 11:59 -0500

csiph-web