天天看點

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

// innerclasses/Outer1.java

// TIJ4 Chapter Innerclasses, Exercise 1, page 347

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 }

}

// innerclasses/Ex20.java

// TIJ4 Chapter Innerclasses, Exercise 20, page 367

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

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

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

// use args 5000 for example

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

// 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

// 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

// 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

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

 }

}