Composition syntax

Bruce Eckel's Thinking in Java Contents | Prev | Next

Until now, composition has been used quite frequently. You simply place object handles inside new classes. For example, suppose you’d like an object that holds several String objects, a couple of primitives and an object of another class. For the non-primitive objects, just put handles inside your new class, and for the primitives just define them inside your class: (See page 97 if you have trouble executing this program.)

//: SprinklerSystem.java
// Composition for code reuse
package c06;
 
class WaterSource {
  private String s;
  WaterSource() {
    System.out.println("WaterSource()");
    s = new String("Constructed");
  }
  public String toString() { return s; }
}
 
public class SprinklerSystem {
  private String valve1, valve2, valve3, valve4;
  WaterSource source;
  int i;
  float f;
  void print() {
    System.out.println("valve1 = " + valve1);
    System.out.println("valve2 = " + valve2);
    System.out.println("valve3 = " + valve3);
    System.out.println("valve4 = " + valve4);
    System.out.println("i = " + i);
    System.out.println("f = " + f);
    System.out.println("source = " + source);
  }
  public static void main(String[] args) {
    SprinklerSystem x = new SprinklerSystem();
    x.print();
  }
} ///:~ 

One of the methods defined in WaterSource is special: toString( ). You will learn later that every non-primitive object has a toString( ) method, and it’s called in special situations when the compiler wants a String but it’s got one of these objects. So in the expression:

valve1 = null
valve2 = null
valve3 = null
valve4 = null
i = 0
f = 0.0
source = null

  1. At the point the objects are defined. This means that they’ll always be initialized before the constructor is called.
  2. In the constructor for that class
  3. Right before you actually need to use the object. This can reduce overhead, if there are situations where the object doesn’t need to be created.
All three approaches are shown here:

//: Bath.java
// Constructor initialization with composition
 
class Soap {
  private String s;
  Soap() {
    System.out.println("Soap()");
    s = new String("Constructed");
  }
  public String toString() { return s; }
}
 
public class Bath {
  private String 
    // Initializing at point of definition:
    s1 = new String("Happy"), 
    s2 = "Happy", 
    s3, s4;
  Soap castille;
  int i;
  float toy;
  Bath() {
    System.out.println("Inside Bath()");
    s3 = new String("Joy");
    i = 47;
    toy = 3.14f;
    castille = new Soap();
  }
  void print() {
    // Delayed initialization:
    if(s4 == null)
      s4 = new String("Joy");
    System.out.println("s1 = " + s1);
    System.out.println("s2 = " + s2);
    System.out.println("s3 = " + s3);
    System.out.println("s4 = " + s4);
    System.out.println("i = " + i);
    System.out.println("toy = " + toy);
    System.out.println("castille = " + castille);
  }
  public static void main(String[] args) {
    Bath b = new Bath();
    b.print();
  }
} ///:~ 

Note that in the Bath constructor a statement is executed before any of the initializations take place. When you don’t initialize at the point of definition, there’s still no guarantee that you’ll perform any initialization before you send a message to an object handle – except for the inevitable run-time exception.

Here’s the output for the program:

Inside Bath()
Soap()
s1 = Happy
s2 = Happy
s3 = Joy
s4 = Joy
i = 47
toy = 3.14
castille = Constructed

When print( ) is called it fills in s4 so that all the fields are properly initialized by the time they are used.



Comments

  • THE CROPS IN OHIO. - Article - NYTimes.com

    Posted by icnosewarch.ru on 12/12/2012 11:08am

    By WebOsPublisher Business man icon set. Business man icon set. Stock Photo Stock Image Clipart Vector by lirch - Royalty Free var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-231595-1']); _gaq.push(['_trackPageview']); (function() var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s[removed].insertBefore(ga, s); )(); section -- section -- Business man icon set. Stock Photo Stock Image Clipart World’s largest 3D Model and Stock Photo resource site! All Products --------------------- 3D Models Stock Photos / Images Textures Tutorials --------------------- Blueprints Materials / Shaders Motion Capture Plug-ins Sound Effects --------------------- Blog Articles Stock Photo Image Business man icon set. Stock Photo Image Information Product ID: 588209 Keywords: abstract, action, activity, body, business, design, element, energy, figure, graphic, green, human, icon, set, idea, illustration, isolated, lifestyle, men, motion, outline, people, shape, sign, silhouette, style, symbol, template, puzzle, piece Copyright: lirch Added on: 1/31/2012 Category: Stock Photos / Images Object Symbols Short URL: Share: Add to lightbox Like it? Yes | No Preview Watermarks and JPG compression artifacts are removed upon purchase. Details License DetailsRoyalty Free - Can be used commercially Pixels @ 600dpi - JPG Price (USD) X-Small: 400x400 $2.00 Small: 800x800 $4.00 Medium: 1600x1600 $8.00 Large: 5000x5000 $12.00 Vector formats available Vector: eps $15.00 Extended License Extended: 5000x5000 + vector $250.00 Why buy stock images from The3dStudio.com? No "credits" No subscription plans No minimum purchase required Buy only what you need, when you need it Pay securely with a credit card Download instantly after checkout Free and fast support seven days a week Earn 5% back in Member Loyalty Rewards Related items View all $2.00 jpg eps $2.00 jpg $2.00 jpg eps $2.00 jpg eps $2.00 jpg eps $2.00 jpg eps $2.00 jpg eps $2.00 jpg News Room | End User License Agreement | Privacy Policy | Site MapCopyright © 1996-2012 The3dStudio.comTM, Inc. All rights reserved. The3dStudio.comTM, Inc. does not make 3ds max® software and is not affiliated with Autodesk®

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds