Think in java 答案_Chapter 7(-)

阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx

Exercise 1

/****************** Exercise 1 *****************
 * Add a new method in the base class of
 * Shapes.java that prints a message, but don't
 * override it in the derived classes. Explain
 * what happens. Now override it in one of the
 * derived classes but not the others, and see
 * what happens. Finally, override it in all the
 * derived classes.
 ***********************************************/
class Shape {
 void draw() {}
 void erase() {}
 void print() {
    System.out.println("Base-class print()");
 }
}
 
class Circle extends Shape {
 void draw() {
    System.out.println("Circle.draw()");
 }
 void erase() {
    System.out.println("Circle.erase()");
 }
 void print() {
    System.out.println("Circle.print()");
 }
}
 
class Square extends Shape {
 void draw() {
    System.out.println("Square.draw()");
 }
 void erase() {
    System.out.println("Square.erase()");
 }
 void print() {
    System.out.println("Square.print()");
 }
}
 
class Triangle extends Shape {
 void draw() {
    System.out.println("Triangle.draw()");
 }
 void erase() {
    System.out.println("Triangle.erase()");
 }
 void print() {
    System.out.println("Triangle.print()");
 }
}
 
public class E01_NewShapeMethod {
 public static void main(String args[]) {
    Shape[] s = {
      new Circle(), new Square(), new Triangle(),
    };
    // Make polymorphic method calls:
    for(int i = 0; i < s.length; i++) {
      s[i].draw();
      s[i].erase();
      s[i].print();
    }
 }
}   
//+M java E01_NewShapeMethod
**The above code is the final version, with print( ) overriden in all classes.
**With print( ) defined only in the base class, the output is:
Circle.draw()
Circle.erase()
Base-class print()
Square.draw()
Square.erase()
Base-class print()
Triangle.draw()
Triangle.erase()
Base-class print()
 
** Since the base-class version is not being overridden, it is used everywhere.
**With print( ) overridden in Circle, the output is:
Circle.draw()
Circle.erase()
Circle.print()
 
Square.draw()
 
Square.erase()
 
Base-class print()
 
Triangle.draw()
 
Triangle.erase()
 
Base-class print()
**The overridden version is used in Circle, and the default base-class version is used everywhere else.
**If print( ) is overridden everywhere, the result is:
Circle.draw()
Circle.erase()
Circle.print()
Square.draw()
Square.erase()
Square.print()
Triangle.draw()
Triangle.erase()
Triangle.print()
**Thus, the overriden version will always be used if it is available.
Exercise 2
/****************** Exercise 2 *****************
 * Add a new type of Shape to Shapes.java and
 * verify in main() that polymorphism works for
 * your new type as it does in the old types.
 ***********************************************/
class Tetrahedron extends Shape {
 void draw() {
    System.out.println("Tetrahedron.draw()");
 }
 void erase() {
    System.out.println("Tetrahedron.erase()");
 }
 void print() {
    System.out.println("Tetrahedron.print()");
 }
}
 
public class E02_NewShapeType {
 public static void main(String args[]) {
    Shape[] s = {
      new Circle(), new Square(), new Triangle(),
      new Tetrahedron()
    };
    // Make polymorphic method calls:
    for(int i = 0; i < s.length; i++) {
      s[i].draw();
      s[i].erase();
      s[i].print();
    }
 }
}   
//+M java E02_NewShapeType
**Since the other shape definitions are in the same directory (default package) we can just add the new shape and override the methods. The code in the for loop is unchanged from the previous example. The output is:
Circle.draw()
Circle.erase()
Circle.print()
Square.draw()
Square.erase()
Square.print()
Triangle.draw()
Triangle.erase()
Triangle.print()
Tetrahedron.draw()
Tetrahedron.erase()
Tetrahedron.print()
Exercise 3
/****************** Exercise 16 *****************
 * Change Music3.java so that what() becomes the
 * root Object method toString(). Try printing
 * the Instrument objects using
 * System.out.println() (without any casting).
 ***********************************************/
class Instrument {
 public void play() {
    System.out.println("Instrument.play()");
 }
 public String toString() {
    return "Instrument";
 }
 public void adjust() {}
}
 
class Wind extends Instrument {
 public void play() {
    System.out.println("Wind.play()");
 }
 public String toString() {
    return "Wind";
 }
 public void adjust() {}
}
 
class Percussion extends Instrument {
 public void play() {
    System.out.println("Percussion.play()");
 }
 public String toString() {
    return "Percussion";
 }
 public void adjust() {}
}
 
class Stringed extends Instrument {
 public void play() {
    System.out.println("Stringed.play()");
 }
 public String toString() {
    return "Stringed";
 }
 public void adjust() {}
}
 
class Brass extends Wind {
 public void play() {
    System.out.println("Brass.play()");
 }
 public void adjust() {
    System.out.println("Brass.adjust()");
 }
}
 
class Woodwind extends Wind {
 public void play() {
    System.out.println("Woodwind.play()");
 }
 public String toString() {
    return "Woodwind";
 }
}
 
public class E03_MusicToString {
 static Instrument[] orchestra = {
   new Wind(),
    new Percussion(),
    new Stringed(),
    new Brass(),
    new Woodwind()
 };
 public static void printAll(Instrument[] orch){
    for(int i = 0; i < orch.length; i++)
      System.out.println(orch[i]);
 }
 public static void main(String args[]) {
    printAll(orchestra);
 }
}   
//+M java E03_MusicToString
**The output is:
Wind
Percussion
Stringed
Wind
Woodwind
Exercise 4
/****************** Exercise 4 *****************
 * Add a new type of Instrument to Music3.java
 * and verify that polymorphism works for your
 * new type.
 ***********************************************/
class Electronic extends Instrument {
 public void play() {
    System.out.println("Electronic.play()");
 }
 public String toString() {
    return "Electronic";
 }
 public void adjust() {}
}
 
public class E04_NewInstrument {
 static Instrument[] orchestra = {
    new Wind(),
    new Percussion(),
    new Stringed(),
    new Brass(),
    new Woodwind(),
    new Electronic()
 };
 public static void main(String args[]) {
    for(int i = 0; i < orchestra.length; i++) {
      orchestra[i].play();
      orchestra[i].adjust();
      System.out.println(orchestra[i]);
    }
 }
}   
//+M java E04_NewInstrument
**The output is:
Wind.play()
Wind
Percussion.play()
Percussion
Stringed.play()
Stringed
Brass.play()
Brass.adjust()
Wind
Woodwind.play()
Woodwind
Electronic.play()
Electronic
Exercise 5
/****************** Exercise 5 *****************
 * Modify Music3.java so that it randomly creates
 * Instrument objects the way Shapes.java does.
 ***********************************************/
class InstrumentGenerator {
 public Instrument next() {
   switch((int) (Math.random() * 6)) {
      default:
      case 0:
        return new Wind();
      case 1:
        return new Percussion();
      case 2:
        return new Stringed();
      case 3:
        return new Brass();
      case 4:
        return new Woodwind();
      case 5:
        return new Electronic();
    }
 }
}
 
public class E05_RandomInstruments {
 public static void main(String args[]) {
    InstrumentGenerator gen =
      new InstrumentGenerator();
    for(int i = 0; i < 20; i++)
      System.out.println(gen.next());
 }
}   
//+M java E05_RandomInstruments
**The idea of a generator is a common one. Every time you call it, it produces a new value, but when you call it you don’t give it any parameters.
**One of the flaws with this design is managing the case statement, which is a bit awkward an error-prone. It would be much nicer if we could just index into an array of objects that could themselves generate the different kinds of instruments. This is possible if we use some features of the Class object. Here’s the more elegant solution (that I didn’t expect you to get!):
// A more sophisticated solution using features
// you'll learn about in later chapters.
class InstrumentGenerator2 {
 Class instruments[] = {
    Wind.class,
    Percussion.class,
    Stringed.class,
    Brass.class,
    Woodwind.class,
    Electronic.class,
 };
 java.util.Random gen = new java.util.Random();
 public Instrument next() {
    try {
      int idx = Math.abs(gen.nextInt())
        % instruments.length;
      return (Instrument) instruments[idx]
        .newInstance();
    } catch(Exception e) {
      System.out.println("e = " + e);
      throw new RuntimeException(
        "Cannot Create Instrument");
    }
 }
}
 
public class E05_RandomInstruments2 {
 public static void main(String args[]) {
    InstrumentGenerator2 gen =
      new InstrumentGenerator2();
    for(int i = 0; i < 20; i++)
      System.out.println(gen.next());
 }
}   
//+M java E05_RandomInstruments
**References to Class objects for each type of instrument can be produced using the .class that you see in the array. The random number generator method nextInt( ) produces positive and negative numbers covering all 32 bits of an int, so it must be forced to be absolute, and the modulus operator will put it in the range of the array. Class objects have a method newInstance( ) which will create objects of their particular class, but these will throw exceptions. Here, I print the exception but then create and throw a RuntimeException (you’ll learn about exceptions in chapter 10) because I consider it a programming error that doesn’t need to be caught at compile-time.
**Note the benefit of this design – if you need to add a new type to the system, you only need to add it in the Class array; everywhere else takes care of itself.
Exercise 6
/****************** Exercise 6 *****************
 * Create an inheritance hierarchy of Rodent:
 * Mouse, Gerbil, Hamster, etc. In the base
 * class, provide methods that are common to all
 * Rodents, and override these in the derived
 * classes to perform different behaviors
 * depending on the specific type of Rodent.
 * Create an array of Rodent, fill it with
 * different specific types of Rodents, and call
 * your base-class methods to see what happens.
 ***********************************************/
class Rodent {
 public void hop() {
    System.out.println("Rodent hopping");
 }
 public void scurry() {
    System.out.println("Rodent scurrying");
  }
 public void reproduce() {
    System.out.println("Making more Rodents");
 }
 public String toString() {
    return "Rodent";
 }
}
 
class Mouse extends Rodent {
 public void hop() {
    System.out.println("Mouse hopping");
 }
 public void scurry() {
    System.out.println("Mouse scurrying");
 }
 public void reproduce() {
    System.out.println("Making more Mice");
 }
 public String toString() {
    return "Mouse";
 }
}
 
class Gerbil extends Rodent {
 public void hop() {
    System.out.println("Gerbil hopping");
 }
 public void scurry() {
    System.out.println("Gerbil scurrying");
 }
 public void reproduce() {
    System.out.println("Making more Gerbils");
 }
 public String toString() {
    return "Gerbil";
 }
}
 
class Hamster extends Rodent {
 public void hop() {
    System.out.println("Hamster hopping");
 }
 public void scurry() {
    System.out.println("Hamster scurrying");
 }
 public void reproduce() {
    System.out.println("Making more Hamsters");
 }
 public String toString() {
    return "Hamster";
 }
}
 
public class E06_Rodents {
 public static void main(String args[]) {
    Rodent[] rodents = {
      new Mouse(),
      new Gerbil(),
      new Hamster(),
    };
    for(int i = 0; i < rodents.length; i++) {
      rodents[i].hop();
      rodents[i].scurry();
      rodents[i].reproduce();
      System.out.println(rodents[i]);
    }
 }
}   
//+M java E06_Rodents
**The output is:
Mouse hopping
Mouse scurrying
Making more Mice
Mouse
Gerbil hopping
Gerbil scurrying
Making more Gerbils
Gerbil
Hamster hopping
Hamster scurrying
Making more Hamsters
Hamster
Exercise 7
/****************** Exercise 7 *****************
 * Modify Exercise 6 so that Rodent is an
 * abstract class. Make the methods of Rodent
 * abstract whenever possible.
 ***********************************************/
abstract class Rodent2 {
 public abstract void hop();
 public abstract void scurry();
 public abstract void reproduce();
}
 
class Mouse2 extends Rodent2 {
 public void hop() {
    System.out.println("Mouse hopping");
 }
 public void scurry() {
    System.out.println("Mouse scurrying");
 }
 public void reproduce() {
    System.out.println("Making more Mice");
 }
 public String toString() {
    return "Mouse";
 }
}
 
class Gerbil2 extends Rodent2 {
 public void hop() {
    System.out.println("Gerbil hopping");
 }
 public void scurry() {
    System.out.println("Gerbil scurrying");
 }
 public void reproduce() {
    System.out.println("Making more Gerbils");
 }
 public String toString() {
    return "Gerbil";
 }
}
 
class Hamster2 extends Rodent2 {
 public void hop() {
    System.out.println("Hamster hopping");
 }
 public void scurry() {
    System.out.println("Hamster scurrying");
 }
 public void reproduce() {
    System.out.println("Making more Hamsters");
 }
 public String toString() {
    return "Hamster";
 }
}
 
 
public class E07_AbstractRodent {
 public static void main(String args[]) {
    Rodent2[] rodents = {
      new Mouse2(),
      new Gerbil2(),
      new Hamster2(),
    };
    for(int i = 0; i < rodents.length; i++) {
      rodents[i].hop();
      rodents[i].scurry();
      rodents[i].reproduce();
      System.out.println(rodents[i]);
    }
 }
}   
//+M java E07_AbstractRodent
**This produces the same output as the previous example. Note that toString( ) is a method of the root class Object and thus can be left out of the abstract base class.
 
  • 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、付费专栏及课程。

余额充值