HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

"Singletons, N-tons and Static-only Classes"
Vol. 3, Issue 4, p. 66


Listing 1: My implementation of part of the java.lang.System class.
//Note use of static member variables, a private constructor and a 
//static initializer block.  
//NOTE: This not how the Java Core API source code implements //this class. 
This is to demonstrate using a public static   
//interface to make a static-only class.  

package java.lang;  

import java.io.*;  

public class System {  
  public final static InputStream in = getIn();  
  public final static PrintStream out = getOut();  
  public final static PrintStream err = getErr();  

  static {  
    // Load native implementation of getXYZ() methods  

  private static native InputStream getIn();  
  private static native InputStream getOut();  
  private static native InputStream getErr();  

  private System() { }  


Listing 2: Implementation of an N-ton class.
//Features include restricted constructor, finite number of public 
//static objects representing the N objects, static initializer 
//block initializing the objects.  
public class Color {  
  int red, green, blue;  

  private Color(int r, int g, int b) {  
    red = r;  
    green = g;  
    blue = b;  

  public static Color Red;  
  public static Color Green;  
  public static Color Blue;  
  public static Color Purple;  
  public static Color Orange;  

  static {  
    Red = new Color(255, 0, 0);  
    Green = new Color(0, 255, 0);  
    Blue = new Color(0, 0, 255);  

Listing 3: Part of the Toolkit class. Uses N-ton pattern to support replaceablity.
package java.awt;  

public abstract class Toolkit {  

  private static Toolkit theToolkit;  

  static {  
    try {  
      String toolkitClassName =  
      Class clsToolkit = Class.forName(toolkitClassName);  
      theToolkit = clsToolkit.newInstance();  
    } catch (Exception e) {  
      theToolkit = null;  

  public static Toolkit getDefaultToolkit() {  
    if(theToolkit == null)  
      throw new RuntimeException("No toolkit exists!");  

    return theToolkit;  


All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.