`

THINKING IN JAVA(4TH) 答案免費分享 chapter 10 Inner Classes

阅读更多

// innerclasses/Outer1.java
// TIJ4 Chapter Innerclasses, Exercise 1, page 347
/* Write a class named Outer that contains an inner class named Innet.
* Add a method to Outer that returns an object of type Inner. In main(),
* create and initialize a reference to an Inner.
*/

public class Outer1 {
 class Inner {
  Inner() { System.out.println("Inner()"); }
 }
 Outer1() { System.out.println("Outer1()"); }
 // make an Inner from within a non-static method of outer class:
 Inner makeInner() {
  return new Inner();
 }
 public static void main(String[] args) {
  Outer1 o = new Outer1();
  Inner i = o.makeInner();
 }
}

 


// innerclasses/Sequence2.java
// TIJ4 Chapter Innerclasses, Exercise 2, page 350
/* Create a class that holds a String, and has a toString() method that
* displays this String. Add several instances of your new class to a
* Sequence ojbect, then display them.
*/

class Word {
 private String word;
 public Word(String s) { word = s; }
 public String toString() { return word; }
}

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

public class Sequence2 {
 private Object[] items;
 private int next = 0;
 public Sequence2(int size) { items = new Object[size]; }
 public void add(Object x) {
  if(next < items.length)
   items[next++] = x;
 }
 private class SequenceSelector implements Selector {
  private int i = 0;
  public boolean end() { return i == items.length; }
  public Object current() { return items[i]; }
  public void next() { if(i < items.length) i++; }
 }
 public Selector selector() {
  return new SequenceSelector();
 }
 public static void main(String[] args) {
  Sequence2 sequence = new Sequence2(10);
  for(int i = 0; i < 10; i++)
   sequence.add(new Word(Integer.toString(i)));
  Selector selector = sequence.selector();
  while(!selector.end()) {
   System.out.print(selector.current() + " ");
   selector.next();
  }
  Word w1 = new Word("Peace");
  Word w2 = new Word("Love");
  Word w3 = new Word("Easter");
  Sequence2 message = new Sequence2(3);
  message.add(w1);
  message.add(w2);
  message.add(w3);
  Selector sel = message.selector();
  while(!sel.end()) {
   System.out.print(sel.current() + " ");
   sel.next();
  }
  
 }
}

 


// innerclasses/Outer3.java
// TIJ4 Chapter Innerclasses, Exercise 3, page 350
/* Modify Exercise 1 so that Outer has a private String field (initialized
* by the constructor), and Inner has a toString() that displays this field.
* Create an object of type Inner and display it.
*/

public class Outer3 {
 private String s;
 class Inner3 {
  Inner3() { System.out.println("Inner()"); }
  public String toString() { return s; }
 }
 Outer3(String s) {
  System.out.println("Outer1()");
  this.s = s;
 }
 Inner3 makeInner3() {
  return new Inner3();
 }
 public static void main(String[] args) {
  Outer3 o = new Outer3("Hi is risen!");
  Inner3 i = o.makeInner3();
  System.out.println(i.toString());
 }
}

 

// innerclasses/Sequence4.java
// TIJ4 Chapter Innerclasses, Exercise 4, page 352
/* Add a method to the class Sequence.SequenceSelector that produces the
* reference to the outer class Sequence.
*/

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

public class Sequence4 {
 private Object[] items;
 private int next = 0;
 // to test SequenceSelector sequence4() in main():
 public void test() { System.out.println("Sequence4.test()"); }
 public Sequence4(int size) { items = new Object[size]; }
 public void add(Object x) {
  if(next < items.length)
   items[next++] = x;
 }
 private class SequenceSelector implements Selector {
  private int i = 0;
  public boolean end() { return i == items.length; }
  public Object current() { return items[i]; }
  public void next() { if(i < items.length) i++; }
  // method to produce outer class reference:
  public Sequence4 sequence4() { return Sequence4.this; }
 }
 public Selector selector() {
  return new SequenceSelector();
 }
 public static void main(String[] args) {
  Sequence4 sequence = new Sequence4(10);
  for(int i = 0; i < 10; i++)
   sequence.add(Integer.toString(i));
  Selector selector = sequence.selector();
  while(!selector.end()) {
   System.out.print(selector.current() + " ");
   selector.next();
  }
  // cast and test:
  ((SequenceSelector)selector).sequence4().test();
 }
}

 


// innerclasses/OtherOuter.java
// TIJ4 Chapter Innerclasses, Exercise 5, page 352
/* Create a class with an inner class. In a separate class, make an
* instance of the inner class.
*/

class Outer {
 class Inner {
  Inner() { System.out.println("Outer.Inner()"); }
 }
}


public class OtherOuter {
 public static void main(String[] args) {
  // must first create outer class object:
  Outer o = new Outer();
  // then create inner class object:
  Outer.Inner i = o.new Inner();  
 }
}

 


// innerclasses/Ex6.java
// TIJ4 Chapter Innerclasses, Exercise 6, page 353
/* Create an interface with at least one method, in its own package. Create
* a class in a separate package. Add a protected inner class that
* implements the interface. In a third package, inherit from your class and
* inside a method, return an object of the protected inner class, upcasting
* to the interface during the return.
*/

/* // in separate package:
* public interface Ex6Interface {
* String say();
* }
*
* // and in a second package:
* public class Ex6Base {
* protected class Ex6BaseInner implements Ex6Interface {
*  // need public constructor to create one in Ex6Base child:
*  public Ex6BaseInner() { }
*  public String say() { return "Hi"; }
* }
* }
*/

import innerclasses.ex6Interface.*;
import innerclasses.ex6Base.*;

public class Ex6 extends Ex6Base {
 Ex6Interface getBaseInner() {
  return this.new Ex6BaseInner();
 }
 public static void main(String[] args) {
  Ex6 ex = new Ex6();
  System.out.println(ex.getBaseInner().say());
 }
}

 


// innerclasses/Outer7.java
// TIJ4 Chapter Innerclasses, Exercise 7, page 354
/* Create a class with a private field and a private method. Create an
* inner class with a method that modifies the outer-class field and calls
* the outer class method. In a second outer-class method, create an object
* of the inner class and call its method, then show the effect on the
* outer-class object.
*/

class Outer7 {
 private int i = 1;
 private void hi() { System.out.println("Outer hi"); }
 class Inner {
  void modifyOuter() {
   oi *= 2;
   hi();
  }
 }
 public void showOi() { System.out.println(oi); }
 void testInner() {
  Inner in = new Inner();
  in.modifyOuter();
 }
 public static void main(String[] args) {
  Outer7 ut = new Outer7();
  out.showOi();
  out.testInner();
  out.showOi();
 }
}

 

// innerclasses/Outer8.java
// TIJ4 Chapter Innerclasses, Exercise 8, page 354
/* Determine whether an outer class has access to the private elements of
* its inner class.
*/

class Outer8 {
 class Inner {
  private int ii1 = 1;
  private int ii2 = 2;
  private void showIi2() { System.out.println(ii2); }
  private void hi() { System.out.println("Inner hi"); }
  }
 // Need to create objects to access private elements of Inner:
 int i = new Inner().ii1;
 void showOi() { System.out.println(oi); }
 void showIi2() { new Inner().showIi2(); }
 void outerHi() { new Inner().hi(); }
 public static void main(String[] args) {
  Outer8 ut = new Outer8();
  out.showOi();
  out.showIi2();
  out.outerHi();
 }
}

 


// innerclasses/Ex9.java
// TIJ4 Chapter Innerclasses, Exercise 9, page 356
/* Create an interface with at least one method, and implement that
* interface by defining an inner class within a method, which returns a
* reference to your interface.
*/

interface Ex9Interface {
 void say(String s);
}

public class Ex9 {
 Ex9Interface f() {
  class Inner implements Ex9Interface {
   public void say(String s) {
    System.out.println(s);
   }
  }
  return new Inner();
 }
 public static void main(String[] args) {
  Ex9 x = new Ex9();
  x.f().say("hi");
 }
}

 


// innerclasses/Ex10.java
// TIJ4 Chapter Innerclasses, Exercise 10, page 356
/* Repeat the previous exercise but define the inner class within a
* scope with scope within a method.
*/

interface Ex10Interface {
 void say(String s);
}

public class Ex10 {
 Ex10Interface f(boolean b) {
  if(b) {
   class Inner implements Ex10Interface {
    public void say(String s) {
     System.out.println(s);
    }
   }
   return new Inner();
  }
  return null;
 }
 public static void main(String[] args) {
  Ex10 x = new Ex10();
  x.f(true).say("hi");
 }
}

 

// innerclasses/Ex11.java
// TIJ4 Chapter Innerclasses, Exercise 11, page 356
/* Create a private inner class that implements a public interface.
* Write a method that returns a reference to an instance of the private
* inner class, upcast to the interface. Show that the inner class is
* completely hidden by trying to downcast to it.
*/

/* public interface Ex11Interface {
* void say(String s);
* }
*/

class Test {
 private class Inner implements Ex11Interface {
  public void say(String s) {
   System.out.println(s);
  }
 }
 Ex11Interface f() {
  return new Inner();
 }
}
public class Ex11 {
 public static void main(String[] args) {
  Test t = new Test();
  t.f().say("hi");
  // Error: cannot find symbol: class Inner:
  // ((Inner)t.f()).say("hello");
 }
}

 

 

// innerclasses/Outer12.java
// TIJ4 Chapter Innerclasses, Exercise 12, page 361
/* Repeat Exercise 7 using an anonymous inner class.
* (Exercise 7: Create a class with a private field and a private method.
* Create an inner class with a method that modifies the outer-class field  * and calls the outer class method. In a second outer-class method, create
* an object of the inner class and call its method, then show the effect on
* the outer-class object.)
*/

interface Inner12 {
 void modifyOuter();
}

public class Outer12 {
 private int i = 1;
 private void hi() { System.out.println("Outer hi"); }
 public Inner12 inner() {
  return new Inner12() {
   public void modifyOuter() {
    oi *= 2;
    hi();
   }
  };
 }
 public void showOi() { System.out.println(oi); }
 public static void main(String[] args) {
  Outer12 ut = new Outer12();
  out.showOi();
  out.inner().modifyOuter();
  out.showOi();
 }
}

 

// innerclasses/Outer13.java
// TIJ4 Chapter Innerclasses, Exercise 13, page 361
/* Repeat Exercise 9 using an anonymous inner class.
* (Exercise 9: Create an interface with at least one method, and implement
* that interface by defining an inner class within a method, which returns
* a reference to your interface.)
*/

interface Ex13Interface {
 String say(String s);
}

public class Outer13 {
 Ex13Interface f() {
  return new Ex13Interface() {
   public String say(String s) { return s; }
  };
 }
 public static void main(String[] args) {
  Outer13 o = new Outer13();
  System.out.println(o.f().say("Hi"));
 }
}

 

 

// innerclasses/HorrorShow14.java
// TIJ4 Chapter Innerclasses, Exercise 14, page361
/* Modify interfaces/HorrorShow.java to implement DangerousMonster and
* Vampire using anonymous classes.
*/
import static org.greggordon.tools.Print.*;

interface Monster {
 void menace();
}

interface DangerousMonster extends Monster {
 void destroy();
}

interface Lethal {
 void kill();
}

class DragonZilla implements DangerousMonster {
 public void menace() {}
 public void destroy() {}
}

interface Vampire extends DangerousMonster, Lethal {
 void drinkBlood();
}

class VeryBadVampire implements Vampire {
 public void menace() {}
 public void destroy() {}
 public void kill() {}
 public void drinkBlood() {}
}

public class HorrorShow14 {
 static void u(Monster b) { b.menace(); }
 static void v(DangerousMonster d) {
  d.menace();
  d.destroy();
 }
 static void w(Lethal l) { l.kill(); }
 public DangerousMonster monsterMaker() {
  return new DangerousMonster() {
   public void menace() { println("DangerousMonster Menace"); }
   public void destroy() { println("DangerousMonster Destroy"); }
  };
 }
 public Vampire vampireMaker() {
  return new Vampire() {
   public void menace() { println("Vampire Menace"); }
   public void destroy() { println("Vampire Destroy"); }
   public void kill() { println("Vampire Kill"); }
   public void drinkBlood() { println("Vampire DrinkBlood"); }
  };
 } 
 public static void main(String[] args) {
  HorrorShow14 show = new HorrorShow14();
  show.u(show.monsterMaker());
  show.v(show.monsterMaker());
  show.u(show.vampireMaker());
  show.v(show.vampireMaker());
  show.w(show.vampireMaker());
 }
}

 


// innerclasses/Ex15.java
// TIJ4 Chapter Innerclasses, Exercise 15, page361
/* Create a class with a non-default constructor and no default constructor.
* Create a second class that has a method that returns a reference to an
* object of the first class. Create the object that you return by making an
* anonymous inner class that inherits from the first class.
*/

class One {
 private String s;
 One(String s) { this.s = s; }
 public String showS() { return s; }
}

public class Ex15 {
 public One makeOne(String s) {
  return new One(s) { };
 }
 public static void main(String[] args) {
  Ex15 x = new Ex15();
  System.out.println(x.makeOne("hi").showS());
 }
}

 


// innerclasses/Cycles.java
// TIJ4 Chapter Innerclasses, Exercise 16, page 364
/* Modify the solution to Exercise 18 from the Interfaces chapter to use
* anonymous inner classes.
* (Exercise 18, Interface: Create a Cycle interface, with implementations
* Unicycle, Bicycle and Tricycle. Create factories for each type of Cycle,
* and code that uses these factories.
*/

import static org.greggordon.tools.Print.*;

interface Cycle {
 void ride();
}

interface CycleFactory {
 Cycle getCycle();
}

class Unicycle implements Cycle {
 private Unicycle() { println("Unicycle()"); }
 public void ride() { println("Ride Unicycle"); }
 public static CycleFactory factory =
  new CycleFactory() {
   public Cycle getCycle() { return new Unicycle(); }
  };
}

class Bicycle implements Cycle {
 private Bicycle() { println("Bicycle()"); }
 public void ride() { println("Ride Bicycle"); }
 public static CycleFactory factory =
  new CycleFactory() {
   public Cycle getCycle() { return new Bicycle(); }
  };
}

class Tricycle implements Cycle {
 private Tricycle() { println("Tricycle()"); }
 public void ride() { println("Ride Tricycle"); }
 public static CycleFactory factory =
  new CycleFactory() {
   public Cycle getCycle() { return new Tricycle(); }
  };
}

public class Cycles {
 public static void rideCycle(CycleFactory factory) {
  Cycle c = factory.getCycle();
  c.ride();
 }
 public static void main(String [] args) {
  rideCycle(Unicycle.factory);
  rideCycle(Bicycle.factory);
  rideCycle(Tricycle.factory);
 }
}

 


// innerclasses/Games17.java
// TIJ4 Chapter Innerclasses, Exercise 17, page 364
/* Modify the solution to Exercise 19 from the Interfaces chapter to use
* anonymous inner classes.
* (Exercise 19, Interfaces: Create a framework using Factory Methods
* that performs both coin tossing and dice tossing.
*/
import java.util.*;
import static org.greggordon.tools.Print.*;

interface Games {
 void play();
}

interface GamesFactory {
 Games getGames();
}

class CoinToss implements Games {
 Random rand = new Random();
 public void play() {
  print("Toss Coin: ");
  switch(rand.nextInt(2)) {
   case 0 : println("Heads"); return;
   case 1 : println("Tails"); return;
   default: println("OnEdge"); return;
  }
 }
 public static GamesFactory factory =
  new GamesFactory() {
   public Games getGames() { return new CoinToss(); }
  };
}

class DiceThrow implements Games {
 Random rand = new Random();
 public void play() {
  print("Throw Dice: " + (rand.nextInt(6) + 1)); 
 }
 public static GamesFactory factory =
  new GamesFactory() {
   public Games getGames() { return new DiceThrow(); }
  };
}

public class Games17 {
 public static void playGame(GamesFactory factory) {
  Games g = factory.getGames();
  g.play();
 }
 public static void main(String [] args) {
  playGame(CoinToss.factory);
  playGame(DiceThrow.factory);  
 }
}

 


// innerclasses/Ex18.java
// TIJ4 Chapter Innerclasses, Exercise 18, page 366
/* Create a class containing a nested class. In main(), create an instance of
* the nested class.
*/

public class Ex18 {
 Ex18() { System.out.println("Ex18()"); }
 public static class Ex18Nest1 {
  Ex18Nest1() { System.out.println("Ex18Nest1()"); }
 }
 private static class Ex18Nest2 {
  Ex18Nest2() { System.out.println("Ex18Nest2()"); }
 }
 public static void main(String[] args) {
  Ex18Nest1 en1 = new Ex18Nest1();
  Ex18Nest2 en2 = new Ex18Nest2();
 }
}

 


// innerclasses/Ex19.java
// TIJ4 Chapter Innerclasses, Exercise 19, page 366
/* Create a class containing an inner class that itself contains an inner
* class. Repeat this using nested classes. Note the names of the .class files
* produced by the compiler.
*/

public class Ex19 {
 Ex19() { System.out.println("Ex19()"); }
 private class Ex19Inner {
  Ex19Inner() { System.out.println("Ex19Inner()"); }
  private class Ex19InnerInner {
   Ex19InnerInner() {
    System.out.println("Ex19InnerInner()");
   }
  }
 }
 private static class Ex19Nested {
  Ex19Nested() { System.out.println("Ex19Nested()"); }
  private static class Ex19NestedNested {
   Ex19NestedNested() {
   System.out.println("Ex19NestedNested()");
   }
  }
 }
 public static void main(String[] args) {
  Ex19Nested en = new Ex19Nested();
  Ex19Nested.Ex19NestedNested enn = new Ex19Nested.Ex19NestedNested();
  Ex19 e19 = new Ex19();
  Ex19.Ex19Inner ei = e19.new Ex19Inner();
  Ex19.Ex19Inner.Ex19InnerInner eii = ei.new Ex19InnerInner();
 }
}

/* compiler produces:
* Ex19$Ex19Inner$Ex19InnerInner.class
* Ex19$Ex19Inner.class
* Ex19$Ex19Nested$Ex19NestedNested.class
* Ex19$Ex19Nested.class
* Ex19.class
*/

 

 

// innerclasses/Ex20.java
// TIJ4 Chapter Innerclasses, Exercise 20, page 367
/* Create an interface containing a nested class. Implement this interface and
* create an instance of the nested class.
*/

interface In {
 class Nested {
  Nested() { System.out.println("Nested()"); }
  public void hi() { System.out.println("hi"); } 
 }
}

public class Ex20 implements In {
 public static void main(String[] args) {
  In.Nested in = new In.Nested();
  in.hi();   
 }
}

 


// innerclasses/Ex21.java
// TIJ4 Chapter Innerclasses, Exercise 21, page 367
/* Create an interface that contains a nested class that has a static method that
* calls the methods of your interface and displays the results. Implement your
* interface and pass an instance of your implementation to the method.
*/

interface In {
 String f();
 String g();
 class Nested {
  static void testIn(In i) {
   System.out.println(i.f() + i.g());
  } 
 } 
}

public class Ex21 implements In {
 public String f() { return "hello "; }
 public String g() { return "friend"; }
 public static void main(String[] args) {
  Ex21 x = new Ex21();
  In.Nested.testIn(x);     
 }
}

 


// innerclasses/Ex23.java
// TIJ4 Chapter Innerclasses, Exercise 23, page 371
/* Create an interface U with three methods. Create a class A with a method that
* produces a reference to a U by building an anonymous inner class. Create a second
* class B that contains an array of U. B should have one method that accepts and
* stores a reference to U in the array, a second method that sets a reference in
* the array (specified by the method argument) to null, and a third method that
* moves through the array and calls the methods in U. In main, create a group of A
* objects and a single B. Fill the B with U references produced by the A objects.
* Use the B to call back into all the A objects. Remove some of the U references
* from the B.
*/

interface U {
 void f();
 void g();
 String toString();
}

class A {
 U buildU() {
  return new U() {
   public void f() { System.out.println("f()"); }
   public void g() { System.out.println("g()"); }
   public String toString() { return "I'm a U"; }
  };
 }
}

class B {
 private U[] us;
 B(int i) {
  us = new U[i];
 }
 void addU(U u, int i) {
  us[i] = u;
 }
 void eraseU(int i) {
  us[i] = null;
 }
 void testUs() {
  for(U u : us) {
   u.f();
   u.g();
   u.toString();
  } 
 }
 void showUs() {
  for(U u : us) {
   if(u != null) System.out.println(u.toString());
   else System.out.println("I'm null");
  }
 }
}

public class Ex23 {
 public static void main(String[] args) {
  A a0 = new A();
  A a1 = new A();
  A a2 = new A();
  B b = new B(3);
  b.addU(a0.buildU(), 0);
  b.addU(a1.buildU(), 1);
  b.addU(a2.buildU(), 2);
  b.showUs();
  b.testUs();
  b.eraseU(0);
  b.eraseU(1);
  b.showUs();
 }
}

 


// innerclasses/GreenhouseController24.java
// TIJ4 Chapter Innerclasses, Exercise 24, page 382
/* In GreenhouseControls.java, add Event inner classes that turn fans on and
* off. Configure GreenhouseController.java to use these new Event objects.
*/
// use args 5000 for example
/* solution includes GreenhouseControls24.java, and, in package
* innerclasses.controller, these two files:
* // innerclasses/controller/Controller.java
* // The reusable framework for control systems.
* package innerclasses.controller;
* import java.util.*;
*
* public class Controller {
* // A class from java.util to hold Event objects:
* private List<Event> eventList = new ArrayList<Event>();
* public void addEvent(Event c) { eventList.add(c); }
* public void run() {
*  while(eventList.size() > 0)
*   // Make a copy so you're not modifying the list
*   // while you're selecting the elements in it:
*   for(Event e : new ArrayList<Event>(eventList))
*    if(e.ready()) {
*     System.out.println(e);
*     e.action();
*     eventList.remove(e);
*    }
* }
* }
* and:
* // innerclasses/controller/Event.java
* // The common methods for any control event.
* package innerclasses.controller;
*
* public abstract class Event {
* private long eventTime;
* protected final long delayTime;
* public Event(long delayTime) {
*  this.delayTime = delayTime;
*  start();
* }
* public void start() { // Allows restarting
* }
* public boolean ready() {
*  return System.nanoTime() >= eventTime;
* }
* public abstract void action();
* }
*/


import innerclasses.controller.*;

public class GreenhouseController24 {
 public static void main(String[] args) {
  GreenhouseControls24 gc = new GreenhouseControls24();
  // Instead of hard-wiring, you could parse
  // configuration information from a text file here:
  gc.addEvent(gc.new Bell(900));
  Event[] eventList = {
   gc.new ThermostatNight(0),
   gc.new LightOn(200),
   gc.new FanOn(300),
   gc.new LightOff(400),
   gc.new FanOff(500),
   gc.new WaterOn(600),
   gc.new WaterOff(800),
   gc.new ThermostatDay(1400),
  };
  gc.addEvent(gc.new Restart(2000, eventList));
  if(args.length == 1)
   gc.addEvent(
    new GreenhouseControls24.Terminate(
     new Integer(args[0])));
  gc.run();
 }
}

 


// innerclasses/GreenhouseControls24.java
// TIJ4 Chapter Innerclasses, Exercise 24, page 382
/* In GreenhouseControls.java, add Event inner classes that turn fans on and
* off. Configure GreenhouseController.java to use these new Event objects.
*/
// solution includes GreenHouseController24.java

import innerclasses.controller.*;

public class GreenhouseControls24 extends Controller {
 private boolean fan = false;
 public class FanOn extends Event {
  public FanOn(long delayTime) { super(delayTime); }
  public void action() {
   // Put hardware control code here to
   // physically turn on the fan.
   fan = true;
  }
  public String toString() { return "Fan is on"; }
 }
 public class FanOff extends Event {
  public FanOff(long delayTime) { super(delayTime); }
  public void action() {
   // Put hardware control here to
   // physically turn off the fan.
   fan = false;
  }
  public String toString() { return "Fan is off"; }
 }
 private boolean light = false;
 public class LightOn extends Event {
  public LightOn(long delayTime) { super(delayTime); }
  public void action() {
   // Put hardware control code here to
   // physically turn on the light.
   light = true;
  }
  public String toString() { return "Light is on"; }
 }
 public class LightOff extends Event {
  public LightOff(long delayTime) { super(delayTime); }
  public void action() {
   // Put hardware control here to
   // physically turn off the light.
   light = false;
  }
  public String toString() { return "Light is off"; }
 }
 private boolean water = false;
 public class WaterOn extends Event {
  public WaterOn(long delayTime) { super(delayTime); }
  public void action() {
   // Put hardware control code here
   water = true;
  }
  public String toString() {
   return "Greenhouse water is on";
  }
 }
 public class WaterOff extends Event {
  public WaterOff(long delayTime) { super(delayTime); }
  public void action() {
   // Put hardware control code here
   water = false;
  }
  public String toString() {
   return "Greenhouse water is off";
  }
 }
 private String thermostat = "Day";
 public class ThermostatNight extends Event {
  public ThermostatNight(long delayTime) {
   super(delayTime);
  }
  public void action() {
   // Put hardware control code here
   thermostat = "Night";
  }
  public String toString() {
   return "Thermostat on night setting";
  }
 }
 public class ThermostatDay extends Event {
  public ThermostatDay(long delayTime) {
   super(delayTime);
  }
  public void action() {
   // Put hardware control code here
   thermostat = "Day";
  }
  public String toString() {
   return "Thermostat on day setting";
  }
 }
 // An example of an action() that inserts a
 // new one of itself into the event list:
 public class Bell extends Event {
  public Bell(long delayTime) { super(delayTime); }
  public void action() {
   addEvent(new Bell(delayTime));
  }
  public String toString() { return "Bing!"; }
 }
 public class Restart extends Event {
  private Event[] eventList;
  public Restart(long delayTime, Event[] eventList) {
   super(delayTime);
   this.eventList = eventList;
   for(Event e : eventList)
    addEvent(e);
  }
  public void action() {
   for(Event e : eventList) {
    e.start(); // Rerun each event
    addEvent(e);
   }
   start(); // Rerun this Event
   addEvent(this);
  }
  public String toString() {
   return "Restarting system";
  }
 }
 public static class Terminate extends Event {
  public Terminate(long delayTime) { super(delayTime); }
  public void action() { System.exit(0); }
  public String toString() { return "Terminating"; }
 }
}

 

 
// innerclasses/GreenhouseController25.java
// TIJ4 Chapter Innerclasses, Exercise 25, page 382
/* Inherit from GreenhouseControls in GreenhouseControls.java to add Event
* inner classes that turn water mist generators on and off. Write a new
* version of GreenhouseController.java to use these new Event objects.
*/
// solution includes GreenhouseControls25.java
// use args 5000 for example
import innerclasses.controller.*;

public class GreenhouseController25 {
 public static void main(String[] args) {
  GreenhouseControls25 gc = new GreenhouseControls25();
  // Instead of hard-wiring, you could parse
  // configuration information from a text file here:
  gc.addEvent(gc.new Bell(900));
  Event[] eventList = {
   gc.new ThermostatNight(0),
   gc.new LightOn(200),
   gc.new LightOff(400),
   gc.new WaterOn(600),
   gc.new WaterMistOn(650),
   gc.new WaterMistOff(700),
   gc.new WaterOff(800),
   gc.new ThermostatDay(1400),
  };
  gc.addEvent(gc.new Restart(2000, eventList));
  if(args.length == 1)
   gc.addEvent(
    new GreenhouseControls.Terminate(
     new Integer(args[0])));
  gc.run();
 }
}

 


// innerclasses/GreenhouseControls25.java
// TIJ4 Chapter Innerclasses, Exercise 25, page 382
/* Inherit from GreenhouseControls in GreenhouseControls.java to add Event
* inner classes that turn water mist generators on and off. Write a new
* version of GreenhouseController.java to use these new Event objects.
*/
// solution includes GreenhouseController25.java
import innerclasses.controller.*;

public class GreenhouseControls25 extends GreenhouseControls {
 private boolean waterMist = false;
 public class WaterMistOn extends Event {
  public WaterMistOn(long delayTime) {
   super(delayTime);
  }
  public void action() {
   // Put hardware control code here to
   // physically turn on water mist generator
   waterMist = true;
  }
  public String toString() {
   return "Water mist generator on"; 
  }
 }
 public class WaterMistOff extends Event {
  public WaterMistOff(long delayTime) {
   super(delayTime);
  }
  public void action() {
   // Put hardware control code here to
   // physically turn off water mist generator
   waterMist = false;
  }
  public String toString() {
   return "Water mist generator off";
  }
 }
}

 


// innerclasses/SecondOuter.java
// TIJ4 Chapter Innerclasses, Exercise 26, page 383
/* Create a class with an inner class that has a non-default constructor
* (one that takes arguments). Create a second class with an inner
* class that inherits from the first inner class.
*/

class FirstOuter {
 public class FirstInner {
  FirstInner(String s) {
   System.out.println("FirstOuter.FirstInner() " + s );
  }
 }
}

public class SecondOuter {
 public class SecondInner extends FirstOuter.FirstInner {
  SecondInner(FirstOuter x) {
   x.super("hello");
   System.out.println("SecondOuter.SecondInner()");
  } 
 }
 public static void main(String[] args) {
  FirstOuter fo = new FirstOuter();
  SecondOuter so = new SecondOuter();
  SecondInner si = so.new SecondInner(fo); 
 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics