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); 
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
写在前面的话 引言 1. 前提 2. Java的学习 3. 目标 4. 联机文档 5. 章节 6. 练习 7. 多媒体 8. 源代码 9. 编码样式 10. Java版本 11. 课程和培训 12. 错误 13. 封面设计 14. 致谢 第1章 对象入门 1.1 抽象的进步 1.2 对象的接口 1.3 实现方案的隐藏 1.4 方案的重复使用 1.5 继承:重新使用接口 1.5.1 改善基础类 1.5.2 等价和类似关系 1.6 多形对象的互换使用 1.6.1 动态绑定 1.6.2 抽象的基础类和接口 1.7 对象的创建和存在时间 1.7.1 集合与继承器 1.7.2 单根结构 1.7.3 集合库与方便使用集合 1.7.4 清除时的困境:由谁负责清除? 1.8 违例控制:解决错误 1.9 多线程 1.10 永久性 1.11 Java和因特网 1.11.1 什么是Web? 1.11.2 客户端编程 1.11.3 服务器端编程 1.11.4 一个独立的领域:应用程序 1.12 分析和设计 1.12.1 不要迷失 1.12.2 阶段0:拟出一个计划 1.12.3 阶段1:要制作什么? 1.12.4 阶段2:开始构建? 1.12.5 阶段3:正式创建 1.12.6 阶段4:校订 1.12.7 计划的回报 1.13 Java还是C++? 第2章 一切都是对象 2.1 用句柄操纵对象 2.2 必须创建所有对象 2.2.1 保存在什么地方 2.2.2 特殊情况:主类型 2.2.3 Java中的数组 2.3 绝对不要清除对象 2.3.1 作用域 2.3.2 对象的作用域 2.4 新建数据类型:类 2.4.1 字段和方法 2.5 方法、自变量和返回值 2.5.1 自变量列表 2.6 构建Java程序 2.6.1 名字的可见性 2.6.2 使用其他组件 2.6.3 static关键字 2.7 我们的第一个Java程序 2.8 注释和嵌入文档 2.8.1 注释文档 2.8.2 具体语法 2.8.3 嵌入 2.8.4 @see:引用其他类 2.8.5 类文档标记 2.8.6 变量文档标记 2.8.7 方法文档标记 2.8.8 文档示例 2.9 编码样式 2.10 总结 2.11 练习 第3章 控制程序流程 3.1 使用Java运算符 3.1.1 优先级 3.1.2 赋值 3.1.3 算术运算符 3.1.4 自动递增和递减 3.1.5 关系运算符 3.1.6 逻辑运算符 3.1.7 按位运算符 3.1.8 移位运算符 3.1.9 三元if-else运算符 3.1.10 逗号运算符 3.1.11 字串运算符 3.1.12 运算符常规操作规则 3.1.13 造型运算符 3.1.14 Java没有“sizeof” 3.1.15 复习计算顺序 3.1.16 运算符总结 3.2 执行控制 3.2.1 真和假 3.2.3 反复 3.2.6 中断和继续 3.2.7 切换 3.3 总结 3.4 练习 第4章 初始化和清除 4.1 由构建器保证初始化 4.2 方法过载 4.2.1 区分过载方法 4.2.2 主类型的过载 4.2.3 返回值过载 4.2.4 默认构建器 4.2.5 this关键字 4.3 清除:收尾和垃圾收集 4.3.1 finalize()用途何在 4.3.2 必须执行清除 4.4 成员初始化 4.4.1 规定初始化 4.4.2 构建器初始化 4.5 数组初始化 4.5.1 多维数组 4.6 总结 4.7 练习 第5章 隐藏实施过程 5.1 包:库单元 5.1.1 创建独一无二的包名 5.1.2 自定义工具库 5.1.3 利用导入改变行为 5.1.4 包的停用 5.2 Java访问指示符 5.2.1 “友好的” 5.2.2 public:接口访问 5.2.3 private:不能接触 5.2.4 protected:“友好的一种” 5.3 接口与实现 5.4 类访问 5.5 总结 5.6 练习 第6章 类再生 6.1 合成的语法 6.2 继承的语法 6.2.1 初始化基础类 6.3 合成与继承的结合 6.3.1 确保正确的清除 6.3.2 名字的隐藏 6.4 到底选择合成还是继承 6.6 递增开发 6.7 上溯造型 6.7.1 何谓“上溯造型”? 6.8 final关键字 6.8.1 final数据 6.8.2 final方法 6.8.3 final类 6.8.4 final的注意事项 6.9 初始化和类装载 6.9.1 继承初始化 6.10 总结 6.11 练习 第7章 多形性 7.1 上溯造型 7.1.1 为什么要上溯造型 7.2 深入理解 7.2.1 方法调用的绑定 7.2.2 产生正确的行为 7.2.3 扩展性 7.3 覆盖与过载 7.4 抽象类和
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值