北京交通大学论坛-知行信息交流平台

 找回密码
 注册
快速进入版块与发帖 搜索
查看: 4149|回复: 23

[作业贴] ThinkingInJava第四版第八章练习

[复制链接]
发表于 2011-5-23 16:40 | 显示全部楼层 |阅读模式
一共17题

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

class Cycle{
        void action(){
                System.out.println("Cycle ride");
        }
        int wheels(){
                return 0;}
}

class Unicycle extends Cycle{
        @Override
        void action(){
                System.out.println("Unicycle ride");
        }
        @Override
        int wheels(){
                return 1;
        }
}

class Bicycle extends Cycle{
        @Override
        void action(){
                System.out.println("Bicycle ride");
        }
        @Override
        int wheels(){
                return 2;
        }
        void balance(){
                System.out.println("Bicycle Balanced.");
        }
}

class Tricycle extends Cycle{
        @Override
        void action(){
                System.out.println("Tricycle ride");
        }
        @Override
        int wheels(){
                return 3;
        }
        void balance(){
                System.out.println("Tricycle Balanced.");
        }
}

public class One {
        static void ride(Cycle me){
                me.action();
        }
        public static void main(String[] args){
                Cycle one = new Cycle();
                Unicycle two = new Unicycle();
                Bicycle three = new Bicycle();
                Tricycle four = new Tricycle();
               
                ride(one);
                ride(two);
                ride(three);
                ride(four);
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

import java.util.Random;

class Shape {
  public void draw() {}
  public void erase() {}
  public void test() {System.out.println("Shape.test()");}
}

class Circle extends Shape{
        @Override
        public void draw(){System.out.println("Circle.draw()");}
        @Override
        public void erase(){System.out.println("Circle.erase()");}
        @Override
        public void test(){System.out.println("Circle.test()");}
}

class Square extends Shape{
        @Override
        public void draw(){System.out.println("Square.draw()");}
        @Override
        public void erase(){System.out.println("Square.erase()");}
        @Override
        public void test(){System.out.println("Square.test()");}
}

class Triangle extends Shape{
        @Override
        public void draw(){System.out.println("Triangle.draw()");}
        @Override
        public void erase(){System.out.println("Triangle.erase()");}
        @Override
        public void test(){System.out.println("Triangle.test()");}
}

class RandomShapeGenerator{
        private Random rand = new Random(47);
        public Shape next(){
                switch (rand.nextInt(3)){
                default:
                case 0: return new Circle();
                case 1: return new Square();
                case 2: return new Triangle();
                }
        }
}

public class Two {
        private static RandomShapeGenerator gen = new RandomShapeGenerator();
        public static void main(String[] args){
                Shape[] s = new Shape[9];
                for (int i = 0; i < 9; i++){
                        s[i] = gen.next();
                        s[i].draw();
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

public class Three {
        private static RandomShapeGenerator gen = new RandomShapeGenerator();
        public static void main(String[] args){
                Shape[] s = new Shape[9];
                for (int i = 0; i < 9; i++){
                        s[i] = gen.next();
                        s[i].draw();
                        s[i].test();
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

import java.util.Random;


class Point extends Circle{
        @Override
        public void draw(){System.out.println("Point.draw()");}
        @Override
        public void erase(){System.out.println("Point.erase()");}
        @Override
        public void test(){System.out.println("Point.test()");}
}

class RandomShapeGenerator1{
        private Random rand = new Random(47);
        public Shape next(){
                switch (rand.nextInt(4)){
                default:
                case 0: return new Circle();
                case 1: return new Square();
                case 2: return new Triangle();
                case 3: return new Point();
                }
        }
}

public class Four {
        private static RandomShapeGenerator1 gen = new RandomShapeGenerator1();
        public static void main(String[] args){
                Shape[] s = new Shape[20];
                for (int i = 0; i < 20; i++){
                        s[i] = gen.next();
                        s[i].draw();
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

public class Five {
        static void ride(Cycle me){
                System.out.println(me.wheels());
        }
        public static void main(String[] args){
                Cycle one = new Cycle();
                Unicycle two = new Unicycle();
                Bicycle three = new Bicycle();
                Tricycle four = new Tricycle();
               
                ride(one);
                ride(two);
                ride(three);
                ride(four);
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
//: polymorphism/music3/Music3.java
// An extensible program.
package exercises.Charpter8;
import polymorphism.music.Note;
import static net.mindview.util.Print.*;

class Instrument {
  void play(Note n) { print("Instrument.play() " + n); }
  public String toString() { return "Instrument"; }
  void adjust() { print("Adjusting Instrument"); }
}

class Wind extends Instrument {
  void play(Note n) { print("Wind.play() " + n); }
  public String toString() { return "Wind"; }
  void adjust() { print("Adjusting Wind"); }
}       

class Percussion extends Instrument {
  void play(Note n) { print("Percussion.play() " + n); }
  public String toString() { return "Percussion"; }
  void adjust() { print("Adjusting Percussion"); }
}

class Stringed extends Instrument {
  void play(Note n) { print("Stringed.play() " + n); }
  public String toString() { return "Stringed"; }
  void adjust() { print("Adjusting Stringed"); }
}

class Brass extends Wind {
  void play(Note n) { print("Brass.play() " + n); }
  void adjust() { print("Adjusting Brass"); }
}

class Woodwind extends Wind {
  void play(Note n) { print("Woodwind.play() " + n); }
  public String toString() { return "Woodwind"; }
}       

public class Six {
  // Doesn't care about type, so new types
  // added to the system still work right:
  public static void tune(Instrument i) {
    // ...
    i.play(Note.MIDDLE_C);
  }
  public static void tuneAll(Instrument[] e) {
    for(Instrument i : e)
      tune(i);
  }       
  public static void main(String[] args) {
    // Upcasting during addition to the array:
    Instrument[] orchestra = {
      new Wind(),
      new Percussion(),
      new Stringed(),
      new Brass(),
      new Woodwind()
    };
    tuneAll(orchestra);
    System.out.println(orchestra[1]);
  }
} /* Output:
Wind.play() MIDDLE_C
Percussion.play() MIDDLE_C
Stringed.play() MIDDLE_C
Brass.play() MIDDLE_C
Woodwind.play() MIDDLE_C
*///:~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

import static net.mindview.util.Print.print;
import polymorphism.music.Note;

class Piano extends Wind {
        void play(Note n) { print("Piano.play() " + n); }
        public String toString() { return "Piano"; }
}       

public class Seven {
        public static void tune(Instrument i) {
            // ...
            i.play(Note.MIDDLE_C);
          }
          public static void tuneAll(Instrument[] e) {
            for(Instrument i : e)
              tune(i);
          }       
          public static void main(String[] args) {
                    // Upcasting during addition to the array:
                    Instrument[] orchestra = {
                      new Wind(),
                      new Percussion(),
                      new Stringed(),
                      new Brass(),
                      new Woodwind(),
                      new Piano(),
                    };
                    tuneAll(orchestra);
                  }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

import java.util.Random;

import polymorphism.music.Note;

class RandomShapeGenerator2{
        private Random rand = new Random(47);
        public Instrument next(){
                switch (rand.nextInt(5)){
                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();
                }
        }
}

public class Eight {
        private static RandomShapeGenerator2 gen = new RandomShapeGenerator2();
        public static void tune(Instrument i) {
            // ...
            i.play(Note.MIDDLE_C);
          }
          public static void tuneAll(Instrument[] e) {
            for(Instrument i : e)
              tune(i);
          }       
          public static void main(String[] args) {
                    // Upcasting during addition to the array:
                    Instrument[] orchestra = new Instrument[20];
                    for (int i = 0; i < 20; i++){
                                orchestra[i] = gen.next();
                        }
                    tuneAll(orchestra);
                  }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

class Rodent {
        static long counter;
        static{
                counter = 0;
        }
        public Rodent() {
                System.out.println("Rodent initialized.");
                counter++;
        }
        void bite(){
                System.out.println("Rodent bite");
        }
        void dispose() throws Throwable{
                counter--;
                if (counter == 0){
                        super.finalize();
                }
        }
}

class Mouse extends Rodent{
        public Mouse() {
                System.out.println("Mouse initialized.");
        }
        @Override
        void bite(){
                System.out.println("Mouse bite");
        }
}

class Gerbil extends Rodent{
        public Gerbil() {
                System.out.println("Gerbil initialized.");
        }
        @Override
        void bite(){
                System.out.println("Gerbil bite");
        }
}

class Hamster extends Rodent{
        public Hamster() {
                System.out.println("Hamster initialized.");
        }
        @Override
        void bite(){
                System.out.println("Hamster bite");
        }
}

public class Nine {
        public static void main(String[] args){
                Rodent[] rodents = {
                                new Mouse(),
                                new Gerbil(),
                                new Hamster(),
                };
                for(Rodent t:rodents){
                        t.bite();
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

class First{
        void func1(){
                System.out.println("Func1" + func2());
        }
        String func2(){
                return "First Func2";
        }
}

class Second extends First{
        @Override
        String func2(){
                return "Second Func2";
        }
}

public class Ten {
        static void call(First a){
                a.func1();
        }
        public static void main(String[] args){
                Second second = new Second();
                call (second);
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
//: polymorphism/Sandwich.java
// Order of constructor calls.
package exercises.Charpter8;
import static net.mindview.util.Print.*;

class Meal {
  Meal() { print("Meal()"); }
}

class Bread {
  Bread() { print("Bread()"); }
}

class Cheese {
  Cheese() { print("Cheese()"); }
}

class Lettuce {
  Lettuce() { print("Lettuce()"); }
}

class Lunch extends Meal {
  Lunch() { print("Lunch()"); }
}

class PortableLunch extends Lunch {
  PortableLunch() { print("PortableLunch()");}
}

class Pickle{
          Pickle() { print("Pickle()"); }
        }

public class Eleven extends PortableLunch {
  private Bread b = new Bread();
  private Cheese c = new Cheese();
  private Lettuce l = new Lettuce();
  private Pickle p = new Pickle();
  public Eleven() { print("Sandwich()"); }
  public static void main(String[] args) {
    new Eleven();
  }
} /* Output:
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()
*///:~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

public class Twelve {
        public static void main(String[] args){
                Rodent[] rodents = {
                                new Mouse(),
                                new Gerbil(),
                                new Hamster(),
                };
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:41 | 显示全部楼层
package exercises.Charpter8;

//: polymorphism/ReferenceCounting.java
// Cleaning up shared member objects.
import static net.mindview.util.Print.*;

class Shared {
  private int refcount = 0;
  private static long counter = 0;
  private final long id = counter++;
  public Shared() {
    print("Creating " + this);
  }
  public void addRef() { refcount++; }
  protected void dispose() {
    if(--refcount == 0)
      print("Disposing " + this);
  }
  public String toString() { return "Shared " + id; }
  @Override
        protected void finalize() throws Throwable {
                System.out.println("Shared finalized");
                super.finalize();
        }
}

class Composing {
  private Shared shared;
  private static long counter = 0;
  private final long id = counter++;
  public Composing(Shared shared) {
    print("Creating " + this);
    this.shared = shared;
    this.shared.addRef();
  }
  protected void dispose() {
    print("disposing " + this);
    shared.dispose();
  }
  public String toString() { return "Composing " + id; }
}

public class Thirteen {
  public static void main(String[] args) {
    Shared shared = new Shared();
    Composing[] composing = { new Composing(shared),
      new Composing(shared), new Composing(shared),
      new Composing(shared), new Composing(shared) };
    for(Composing c : composing)
      c.dispose();
    System.gc();//无法强制回收
  }
} /* Output:
Creating Shared 0
Creating Composing 0
Creating Composing 1
Creating Composing 2
Creating Composing 3
Creating Composing 4
disposing Composing 0
disposing Composing 1
disposing Composing 2
disposing Composing 3
disposing Composing 4
Disposing Shared 0
*///:~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:42 | 显示全部楼层
package exercises.Charpter8;

public class Fourteen {
        public static void main(String[] args) throws Throwable{
                Rodent[] rodents = {
                                new Mouse(),
                                new Gerbil(),
                                new Hamster(),
                };
                for(Rodent i:rodents){
                        i.dispose();
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:42 | 显示全部楼层
package exercises.Charpter8;

//: polymorphism/PolyConstructors.java
// Constructors and polymorphism
// don't produce what you might expect.
import static net.mindview.util.Print.*;

class Glyph {
  void draw() { print("Glyph.draw()"); }
  Glyph() {
    print("Glyph() before draw()");
    draw();
    print("Glyph() after draw()");
  }
}       

class RoundGlyph extends Glyph {
  private int radius = 1;
  RoundGlyph(int r) {
    radius = r;
    print("RoundGlyph.RoundGlyph(), radius = " + radius);
  }
  void draw() {
    print("RoundGlyph.draw(), radius = " + radius);
  }
}       

class RectangularGlyph extends Glyph {
          private int radius = 1;
          RectangularGlyph(int r) {
            radius = r;
            print("RectangularGlyph.RectangularGlyph(), radius = " + radius);
          }
          void draw() {
            print("RectangularGlyph.draw(), radius = " + radius);
          }
        }

public class Fifteen {
  public static void main(String[] args) {
    new RectangularGlyph(5);
  }
} /* Output:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
*///:~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:42 | 显示全部楼层
package exercises.Charpter8;

//: polymorphism/Transmogrify.java
// Dynamically changing the behavior of an object
// via composition (the "State" design pattern).
import static net.mindview.util.Print.*;

class Actor {
  public void act() {}
}

class HappyActor extends Actor {
  public void act() { print("HappyActor"); }
}

class SadActor extends Actor {
  public void act() { print("SadActor"); }
}

class Stage {
  private Actor actor = new HappyActor();
  public void change() { actor = new SadActor(); }
  public void performPlay() { actor.act(); }
}

class AlertStatus{
        int status = 0;
        public String getStatus() {
                switch (status) {
                case 0:        return "Nothing";
                case 1:        return "Warning";
                case 2:        return "Alert";
                default:
                        break;
                }
                return null;
        }
        public void setStatus(int status) {
                if ((status < 3)&&(status >= 0))
                        this.status = status;
        }
}

class Starship{
        private AlertStatus alert = new AlertStatus();
        @Override
        public String toString() {
                return getAlert().getStatus();
        }
        private AlertStatus getAlert() {
                return alert;
        }
        public void setAlert(int status) {
                this.alert.setStatus(status);
        }
       
}

public class Sixteen {
  public static void main(String[] args) {
    Starship a = new Starship();
    a.setAlert(2);
    System.out.println(a);
    a.setAlert(1);
    System.out.println(a);
    a.setAlert(0);
    System.out.println(a);
  }
} /* Output:
HappyActor
SadActor
*///:~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 16:42 | 显示全部楼层
package exercises.Charpter8;

public class Seventeen {
        public static void main(String[] args){
                Cycle me[] = {
                                new Cycle(),
                                new Unicycle(),
                                new Bicycle(),
                                new Tricycle(),
                };
//                ((Bicycle)me[0]).balance();
//                ((Bicycle)me[1]).balance();
                ((Bicycle)me[2]).balance();
                ((Tricycle)me[3]).balance();
        }
}
回复 支持 反对

使用道具 举报

发表于 2011-5-23 18:16 | 显示全部楼层
楼主有PDF版本吗?发给我呗 263782783@163.com 感激不尽那
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-23 20:26 | 显示全部楼层
ohkayone 发表于 2011-5-23 18:16
楼主有PDF版本吗?发给我呗  感激不尽那

唉,没有啊,只有书,当当买的。前一阵子学苑卖盗版的半价出售,有两三本呢
回复 支持 反对

使用道具 举报

发表于 2011-5-23 20:27 | 显示全部楼层
ohkayone 发表于 2011-5-23 18:16
楼主有PDF版本吗?发给我呗  感激不尽那

我等会儿给你发一个~~
回复 支持 反对

使用道具 举报

发表于 2011-5-23 22:23 | 显示全部楼层
goooodbye 发表于 2011-5-23 20:27
我等会儿给你发一个~~

谢谢你,我收到了 谢谢
回复 支持 反对

使用道具 举报

发表于 2011-5-23 22:23 | 显示全部楼层
lynx 发表于 2011-5-23 20:26
唉,没有啊,只有书,当当买的。前一阵子学苑卖盗版的半价出售,有两三本呢 ...

看书看不进去啊
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-5-24 09:55 | 显示全部楼层
ohkayone 发表于 2011-5-23 22:23
看书看不进去啊

看pdf比看书还难看进去的,一会qq响一下,或者看看人人、知行什么的。还是书更专心一点点
回复 支持 反对

使用道具 举报

手机版|北京交通大学论坛-知行信息交流平台 ( BJTUICP备13011901号 )

GMT+8, 2023-11-30 03:42

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表