★ wanayoo — archive 1999 http://www.webtechniques.com/sourcecode/1997/11/java/eckel.lstNouvelle recherche | Portail wanayoo

 
| home | current issue | archives | source code | events | demo express | search | editorial calendar | advertising | customer service | author guidelines | jobs | about

S O U R C E   C O D E / 1997 / 11 / java / eckel.lst

"Java Alley"
by  Bruce Eckel
Web Techniques, November 1997

Web Techniques grants permission to use these listings for private or
commercial use provided that credit to Web Techniques and the author is
maintained within the comments of the source. For questions, contact
editors@web-techniques.com.

JAVA ALLEY

LISTING ONE


//: Parcel1.java
// Creating inner classes
package c07.parcel1;
public class Parcel1 {
  class Contents {
    private int i = 11;
    public int value() { return i; }
  }
  class Destination {
    private String label;
    Destination(String whereTo) {
      label = whereTo;
    }
    String readLabel() { return label; }
  }
  public static void main(String args[]) {
    Parcel1 p = new Parcel1();
    // What can you do with it? Create some
    // objects. Must use instance of outer class
    // to create instances of inner classes:
    Parcel1.Contents c = p.new Contents();
    Parcel1.Destination d =
      p.new Destination("Tanzania");
  }
} ///:~


LISTING TWO


//: Parcel2.java
// Returning a handle to an inner class
package c07.parcel2;
public class Parcel2 {
  class Contents {
    private int i = 11;
    public int value() { return i; }
  }
  class Destination {
    private String label;
    Destination(String whereTo) {
      label = whereTo;
    }
    String readLabel() { return label; }
  }
  public Destination dest(String s) {
    return new Destination(s);
  }
  public Contents cont() { return new Contents(); }
  public static void main(String args[]) {
    Parcel2 p = new Parcel2();
    Parcel2.Contents c = p.cont();
    Parcel2.Destination d = p.dest("Tanzania");
  }
} ///:~


LISTING THREE


//: Parcel3.java
// Returning a handle to an inner class
package c07.parcel3;
abstract class Contents {
  abstract public int value();
}
interface Destination {
  String readLabel();
}
public class Parcel3 {
  private class PContents extends Contents {
    private int i = 11;
    public int value() { return i; }
  }
  protected class PDestination
      implements Destination {
    private String label;
    private PDestination(String whereTo) {
      label = whereTo;
    }
    public String readLabel() { return label; }
  }
  public Destination dest(String s) {
    return new PDestination(s);
  }
  public Contents cont() { 
    return new PContents(); 
  }
}
class Test {
  public static void main(String args[]) {
    Parcel3 p = new Parcel3();
    Contents c = p.cont();
    Destination d = p.dest("Tanzania");
    // Illegal -- can't access private class:
    //! Parcel3.PContents c = p.new PContents();
  }
} ///:~

LISTING FOUR


//: Parcel4.java
// Static inner classes
package c07.parcel4;
abstract class Contents {
  abstract public int value();
}
interface Destination {
  String readLabel();
}
public class Parcel4 {
  private static class PContents extends Contents {
    private int i = 11;
    public int value() { return i; }
  }
  protected static class PDestination
      implements Destination {
    private String label;
    private PDestination(String whereTo) {
      label = whereTo;
    }
    public String readLabel() { return label; }
  }
  public static Destination dest(String s) {
    return new PDestination(s);
  }
  public static Contents cont() {
    return new PContents();
  }
  public static void main(String args[]) {
    Contents c = Parcel4.cont();
    Destination d = Parcel4.dest("Tanzania");
  }
} ///:~


LISTING FIVE


//: Destination.java
package c07.innerscopes;

interface Destination {
  String readLabel();
} ///:~


LISTING SIX


//: Contents.java
package c07.innerscopes;
interface Contents {
  abstract public int value();
} ///:~


LISTING SEVEN


//: Wrapping.java
package c07.innerscopes;
public class Wrapping {
  private int i;
  public Wrapping(int x) { i = x; }
  public int value() { return i; }
} ///:~


LISTING EIGHT


//: Parcel5.java
// Nesting a class within a method
package c07.innerscopes;
public class Parcel5 {
  public Destination dest(String s) {
    class PDestination
        implements Destination {
      private String label;
      private PDestination(String whereTo) {
        label = whereTo;
      }
      public String readLabel() { return label; }
    }
    return new PDestination(s);
  }
  public static void main(String args[]) {
    Parcel5 p = new Parcel5();
    Destination d = p.dest("Tanzania");
  }
} ///:~

LISTING NINE


//: Parcel6.java
// Nesting a class within a scope
package c07.innerscopes;

public class Parcel6 {
  private void internalTracking(boolean b) {
    if(b) {
      class TrackingSlip {
        private String id;
        TrackingSlip(String s) {
          id = s;
        }
        String getSlip() { return id; }
      }
      TrackingSlip ts = new TrackingSlip("slip");
      String s = ts.getSlip();
    }
    // Can't use it here! Out of scope:
    //! TrackingSlip ts = new TrackingSlip("x");
  }
  public void track() { internalTracking(true); }
  public static void main(String args[]) {
    Parcel6 p = new Parcel6();
    p.track();
  }
} ///:~


LISTING TEN


//: Parcel7.java
// A method that returns an anonymous inner class
package c07.innerscopes;

public class Parcel7 {
  public Contents cont() {
    return new Contents() {
      private int i = 11;
      public int value() { return i; }
    }; // Semicolon required in this case
  }
  public static void main(String args[]) {
    Parcel7 p = new Parcel7();
    Contents c = p.cont();
  }
} ///:~


LISTING ELEVEN


return new Contents() {
  private int i = 11;
  public int value() { return i; }
};


LISTING TWELVE


//: Parcel8.java
// An anonymous inner class that calls the 
// base-class constructor
package c07.innerscopes;

public class Parcel8 {
  public Wrapping wrap(int x) {
    return new Wrapping(x) { // Base ctor call
      public int value() {
        return super.value() * 47;
      }
    }; // Semicolon required
  }
  public static void main(String args[]) {
    Parcel8 p = new Parcel8();
    Wrapping w = p.wrap(10);
  }
} ///:~


LISTING THIRTEEN


//: Parcel9.java
// An anonymous inner class that performs 
// initialization. A briefer version
// of Parcel5.java.
package c07.innerscopes;

public class Parcel9 {
  // Argument must be final to use inside 
  // anonymous inner class:
  public Destination dest(final String dest) {
    return new Destination() {
      private String label = dest;
      public String readLabel() { return label; }
    };
  }
  public static void main(String args[]) {
    Parcel9 p = new Parcel9();
    Destination d = p.dest("Tanzania");
  }
} ///:~


LISTING FOURTEEN


//: Parcel10.java
// Using "instance initialization" to perform 
// construction on an anonymous inner class
package c07.innerscopes;

public class Parcel10 {
  public Destination 
  dest(final String dest, final float price) {
    return new Destination() {
      private int cost;
      // Instance initialization for each object:
      {
        cost = Math.round(price);
        if(cost > 100)
          System.out.println("Over budget!");
      }
      private String label = dest;
      public String readLabel() { return label; }
    };
  }
  public static void main(String args[]) {
    Parcel10 p = new Parcel10();
    Destination d = p.dest("Tanzania", 101.395F);
  }
} ///:~


LISTING FIFTEEN


//: Sequence.java
// Holds a sequence of Objects

interface Selector {
  boolean end();
  Object current();
  void next();
}

public class Sequence {
  private Object[] o;
  private int next = 0;
  public Sequence(int size) {
    o = new Object[size];
  }
  public void add(Object x) {
    if(next < o.length) {
      o[next] = x;
      next++;
    }
  }
  private class SSelector implements Selector {
    int i = 0;
    public boolean end() {
      return i == o.length;
    }
    public Object current() {
      return o[i];
    }
    public void next() {
      if(i < o.length) i++;
    }
  }
  public Selector getSelector() {
    return new SSelector();
  }
  public static void main(String args[]) {
    Sequence s = new Sequence(10);
    for(int i = 0; i < 10; i++)
      s.add(Integer.toString(i));
    Selector sl = s.getSelector();    
    while(!sl.end()) {
      System.out.println((String)sl.current());
      sl.next();
    }
  }
} ///:~


LISTING SIXTEEN


//: Event.java
// The common methods for any control event
package c07.controller;

abstract public class Event {
  private long evtTime;
  public Event(long eventTime) {
    evtTime = eventTime;
  }
  public boolean ready() {
    return System.currentTimeMillis() >= evtTime;
  }
  abstract public void action();
  abstract public String description();
} ///:~


LISTING SEVENTEEN


//: Controller.java
// Along with Event, the generic
// framework for all control systems:
package c07.controller;

// This is just a way to hold Event objects.
class EventSet {
  private Event events[] = new Event[100];
  private int index = 0;
  private int next = 0;
  public void add(Event e) {
    if(index >= events.length)
      return; // (Should throw exception)
    events[index++] = e;
  }
  public Event getNext() {
    boolean looped = false;
    int start = next;
    do {
      next = (next + 1) % events.length;
      // See if it has looped to the beginning:
      if(start == next) looped = true;
      // If it loops past start, the list 
      // is empty:
      if((next == (start + 1) % events.length)
         && looped)
        return null;
    } while(events[next] == null);
    return events[next];
  }
  public void removeCurrent() {
    events[next] = null;
  }
}

public class Controller {
  private EventSet es = new EventSet();
  public void addEvent(Event c) { es.add(c); }
  public void run() {
    Event e;
    while((e = es.getNext()) != null) {
      if(e.ready()) {
        e.action();
        System.out.println(e.description());
        es.removeCurrent();
      }
    }
  }
} ///:~


LISTING EIGHTEEN


//: GreenhouseControls.java
// This produces a specific application of the
// control system, all in a single class. Inner
// classes allow you to encapsulate different
// functionality for each type of event.
package c07.controller;

public class GreenhouseControls 
    extends Controller {
  private boolean light = false;
  private boolean water = false;
  private String thermostat = "Day";
  class LightOn extends Event {
    public LightOn(long eventTime) {
      super(eventTime);
    }
    public void action() {
      // Put hardware control code here to 
      // physically turn on the light.
      light = true;
    }
    public String description() {
      return "Light is on";
    }
  }
  class LightOff extends Event {
    public LightOff(long eventTime) {
      super(eventTime);
    }
    public void action() {
      // Put hardware control code here to 
      // physically turn off the light.
      light = false;
    }
    public String description() {
      return "Light is off";
    }
  }
  class WaterOn extends Event {
    public WaterOn(long eventTime) {
      super(eventTime);
    }
    public void action() {
      // Put hardware control code here
      water = true;
    }
    public String description() {
      return "Greenhouse water is on";
    }
  }
  class WaterOff extends Event {
    public WaterOff(long eventTime) {
      super(eventTime);
    }
    public void action() {
      // Put hardware control code here
      water = false;
    }
    public String description() {
      return "Greenhouse water is off";
    }
  }
  class ThermostatNight extends Event {
    public ThermostatNight(long eventTime) {
      super(eventTime);
    }
    public void action() {
      // Put hardware control code here
      thermostat = "Night";
    }
    public String description() {
      return "Thermostat on night setting";
    }
  }
  class ThermostatDay extends Event {
    public ThermostatDay(long eventTime) {
      super(eventTime);
    }
    public void action() {
      // Put hardware control code here
      thermostat = "Day";
    }
    public String description() {
      return "Thermostat on day setting";
    }
  }
  // An example of an action() which inserts a 
  // new one of itself into the event list:
  private int rings;
  class Bell extends Event {
    public Bell(long eventTime) {
      super(eventTime);
    }
    public void action() {
      // Ring bell every 2 seconds, rings times:
      System.out.println("Bing!");
      if(--rings > 0)
        addEvent(new Bell(
          System.currentTimeMillis() + 2000));
    }
    public String description() {
      return "Ring bell";
    }
  }
  class Restart extends Event {
    public Restart(long eventTime) {
      super(eventTime);
    }
    public void action() {
      long tm = System.currentTimeMillis();
      // Instead of hard-wiring, you could parse
      // configuration information from a text
      // file here:
      rings = 5;
      addEvent(new LightOn(tm + 1000));
      addEvent(new LightOff(tm + 2000));
      addEvent(new Bell(tm + 9000));
      addEvent(new WaterOn(tm + 3000));
      addEvent(new WaterOff(tm + 8000));
      addEvent(new ThermostatNight(tm));
      addEvent(new ThermostatDay(tm + 10000));
      // Can even add a Restart object!
      addEvent(new Restart(tm + 20000));
    }
    public String description() {
      return "Restarting system";
    }
  }
  public static void main(String args[]) {
    GreenhouseControls gc = 
      new GreenhouseControls();
    long tm = System.currentTimeMillis();
    gc.addEvent(gc.new Restart(tm));
    gc.run();
  } 
} ///:~




| home | current issue | archives | source code | demo express | events | search | editorial calendar | advertising | customer service | author guidelines | jobs | about




Entire contents copyright 1996-2000 CMP Media Inc.
Read our privacy policy.