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

Thinking in Java 中文第四版+习题答案 写在前面的话 引言 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 抽象类和 立即下载

相关推荐

Thinking in Java(中文版)带有课后题答案完整版

同人类任何语言一样,Java为我们提供了一种表达思想的方式。如操作得当,同其他方式相比,随着问题变得愈大和愈复杂,这种表达方式的方便性和灵活性会显露无遗。 不可将Java简单想象成一系列特性的集合;如孤立地看,有些特性是没有任何意义的。只有在考虑“设计”、而非考虑简单的编码时,才可真正体会到Java的强大。为了按这种方式理解Java,首先必须掌握它与编程的一些基本概念。本书讨论了编程问题、它们为何会成为问题以及Java用以解决它们的方法。所以,我对每一章的解释都建立在如何用语言解决一种特定类型的问题基础上。按这种方式,我希望引导您一步一步地进入Java的世界,使其最终成为您最自然的一种语言。 贯穿本书,我试图在您的大脑里建立一个模型——或者说一个“知识结构”。这样可加深对语言的理解。若遇到难解之处,应学会把它填入这个模型的对应地方,然后自行演绎出答案。事实上,学习任何语言时,脑海里有一个现成的知识结构往往会起到事半功倍的效果。

《Thinking In Java》---第四版 练习题答案

百度网盘下载:https://pan.baidu.com/share/link?shareid=2111776725&uk=2869544179&app=zd 在线查看:http://greggordon.org/java/tij4/solutions.htm Java学习交流QQ群:603654340我们一起学Java! 转载于:https://www.cnblogs.co...

weixin_30254435的博客 508

Thinking in java 练习题答案

Annotated Solution Guide for TIJ4.pdf。Thinking in java 练习题答案。

think in java 第四版

think in java 第四版课后答案 第九章 6 think in java 第四版课后答案 第九章 7 think in java 第四版课后答案 第九章 8 think in java 第四版课后答案 第九章 9 mysql 像Oracle一样 解决方案 Java内存泄漏分析与解决方案 09java10大技术 spring事务属性 你可能不知道的10...

weixin_34221036的博客 230

《Thinking in Java 4th》习题答案

博文链接:https://kencool.iteye.com/blog/186509

thinking in java 原版及其练习答案

本书赢得了全球程序员的广泛赞誉,即使是最晦涩的概念,在Bruce Eckel具有亲和力的文字和小而直接的编程示例面前也会化解于无形。从Java的基础语法到最高级特性(深入的面向对象概念、多线程、自动项目构建、单元测试和调试等),本书都能逐步指导你轻松掌握。最新版本的哦

【Java 基础】Thinking In Java 习题答案(一个外国小gg的)

非常感谢 http://greggordon.org/java/tij4/solutions.htm Tips 这书要一遍遍嚼,怎么也要翻3、5遍,不分初学者、老司机blabla; 不要求都背下来,差不多合上书哪章讲啥重点啥基本都清楚。 建议大家把书上的习题也搞一遍(可以参考国外小gg的)。 参考: Thinking In Java网络在线书阅读地址 来自网络...

一只写代码的狐松鼠 5986

(一)企业微信 - 会话内容存档

企业微信获取会话记录。

专打丶小豆豆的博客 2892

THINKING IN JAVA 第四版 及源码和习题答案

这个版本挺不错的 打出来看着很有感觉 比机械出的那本舒服多了

做真正的自己 1143

避坑指南:RK3568双网口RMII模式DTS配置常见错误与调试技巧

本文详细解析了RK3568双网口RMII模式DTS配置中的常见错误与调试技巧,涵盖时钟配置、PHY识别、复位时序等关键问题。通过实战案例和系统化调试方法,帮助开发者快速解决百兆以太网连接不稳定、PHY识别失败等典型问题,提升开发效率。

weixin_42549037的博客 344

3D Gaussian Splatting的使用

Gaussian splatting 快速生成自己屋子的模型

gootyking的博客 1万+

Thinking in java 4th Edition 习题答案全

http://greggordon.org/java/tij4/solutions.htm 向这位外国大哥致敬了!

Bop to the top! 1万+

脑影像分析入门:如何用一般线性模型(GLM)处理fMRI数据?

本文为神经影像研究入门者详细解析了如何运用一般线性模型(GLM)处理fMRI数据。文章从GLM的核心原理出发,逐步拆解了从实验设计、构建稳健设计矩阵、模型估计与统计推断,到高阶分析及多重比较校正的全流程,并指出了常见陷阱与结果解读要点,是掌握fMRI数据分析基础的关键指南。

weixin_29091445的博客 400

think in java 第四版习题答案

向奋斗者致敬 http://greggordon.org/java/tij4/solutions.htm

jade07的专栏 1340

手把手带你搭建一个语音对话机器人:5分钟定制个人AI小助手

通过本文的简单步骤,你已经掌握了如何用 Python 搭建一个语音对话机器人。我们使用了实现语音识别,利用 OpenAI API 生成对话内容,并通过gTTS将文本转换为语音。整个流程非常简洁,你可以根据自己的需求进一步扩展机器人功能,甚至将其集成到实际的应用场景中。

小蜗牛的珍贵百宝箱 4805

咨询进阶——解读40页公司战略解码方法【附全文阅读】

战略解码是将企业战略转化为可执行计划的关键过程,强调垂直和水平一致性原则。通过KPI指标设计和目标分解,确保战略在各部门和岗位有效落地。解码过程包括战略澄清、目标牵引、绩效分解和承诺签订,输出战略解码图等文件。不同部门根据责任定位(如利润中心、绩效中心)采用差异化考核方式,实现战略有效执行。

cdfunlove的博客 150

Thinking in Java 第四版完整版 第六章练习题 访问权限控制

Thinking in Java 第四版完整版 第六章练习题,记录一下(jdk1.8.0) 1. package com.test.c06; /** * 练习1:在某个包中创建一个类,在这个类所处的包的外部创建该类的一个实例。 * @author admin11 * @date 2018年3月20日 */ public class Exercise601 { } ...

summerSunStart的博客 993

【论文汇总】Diffusion Models视频生成/视频编辑/可控视频生成/跨模态视频生成

本文总结了Diffusion Models视频生成领域相关的工作,目前共收录142篇,持续更新中。

沉迷单车的追风少年 1672

Thinking in java第四版--第2章习题答案--关键字、变量、声明、赋值、初始化、类型转换

Java两大核心机制:     Java虚拟机(Java Virtual Machine):JVM是一个虚拟的计算机,具有指令集并使用不同的存储区域。负责执行指令,管理数据、内存、寄存器。Java虚拟机机制屏蔽了底层运行平台的差别,实现了“一次编译,到处运行”。     垃圾收集机制(Garbage Collection): 垃圾回收:将不再使用的内存空间进行回收。  在 C/C+

xiaowanggedege的专栏 2368

【以太网硬件九】1000base-X是什么?

简要描述1000base-X物理层规范

highman110的博客 1万+

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

THINKING IN JAVA(4TH) 答案免費分享 chapter 11 Holding Your Object

// holding/Ex1.java// TIJ4 Chapter Holding, Exercise 1, page 394/* Create a new class called Gerbil with an int gerbilNumber that's * initialized in the constructor. Give it a method called hop() th...

284

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Thinking in java 习题答案

这个是我在学习thinking in java过程中所做的习题(不全),和大家分享,希望能共同进步以下是下载地址: http://211.155.234.58/coa/download.html     ----------------------------------------------------------------------------------

天堂来客 3057

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Think in java 答案_Chapter 7(-)

阅前声明: http://blog.youkuaiyun.com/heimaoxiaozi/archive/2007/01/19/1487884.aspxExercise 1/****************** Exercise 1 ***************** * Add a new method in the base class of * Shapes.java that pri

为天加朵云... 1294
上一篇: java中怎样反向显示字符串(包含实际开发中的例子),有很多地方值得借鉴
下一篇: THINKING IN JAVA(4TH) 答案免費分享 chapter 11 Holding Your Object
ccfangle
博客等级 码龄20年 1粉丝 75原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值