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

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

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

[复制链接]
发表于 2011-6-4 00:29 | 显示全部楼层 |阅读模式
本帖最后由 lynx 于 2011-6-7 13:56 编辑

一共19题

 楼主| 发表于 2011-6-4 00:29 | 显示全部楼层
package exercises.Charpter9;

abstract 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 One {
        public static void main(String[] args){
                Rodent[] rodents = {
                                new Mouse(),
                                new Gerbil(),
                                new Hamster(),
                };
                for(Rodent t:rodents){
                        t.bite();
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:29 | 显示全部楼层
package exercises.Charpter9;

abstract class TotalAbstract{
       
}

public class Two {
        @SuppressWarnings("unused")
        public static void main(String[] args){
                TotalAbstract a;
//                a = new TotalAbstract();//不能new
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:29 | 显示全部楼层
package exercises.Charpter9;

abstract class Base{
        void print(){}
        public Base() {
                print();
        }
}

class Extend extends Base{
        private int i = 10;
        void print(){
                System.out.println(i);//基类构造函数构造的时候调用了实现,但是i当时还未初始化
        }
}

public class Three {
        @SuppressWarnings("unused")
        public static void main(String[] args){
                Extend test = new Extend();
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:29 | 显示全部楼层
package exercises.Charpter9;

abstract class A{
        abstract void func();
}

class B extends A{
        void func(){
                System.out.println("why is 0?");
        }
}

public class Four {
        public static void main(String[] args){
                A me = new B();
                me.func();
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

import other.Face;

class TestInterface implements Face{

        @Override
        public void func1() {
                // TODO Auto-generated method stub
                System.out.println("Func1");
        }

        @Override
        public void func2() {
                // TODO Auto-generated method stub
                System.out.println("Func2");
        }

        @Override
        public void func3() {
                // TODO Auto-generated method stub
                System.out.println("Func3");
        }
}

public class Five{
        public static void main(String[] args){
                Face test = new TestInterface();
                test.func1();
                test.func2();
                test.func3();
        }
}


other.java
package other;

public interface Face {
        void func1();
        void func2();
        void func3();
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

import other.Face;

public class Six {
        public static void main(String[] args){
                Face test = new TestInterface();
                test.func1();
                test.func2();
                test.func3();
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

interface Rodent1 {
        void bite();
}

class Mouse1 implements Rodent1{
        @Override
        public void bite(){
                System.out.println("Mouse bite");
        }
}

class Gerbil1 implements Rodent1{
        @Override
        public void bite(){
                System.out.println("Gerbil bite");
        }
}

class Hamster1 implements Rodent1{
        @Override
        public void bite(){
                System.out.println("Hamster bite");
                try {
                        Thread.sleep(1000);
                } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}

public class Seven {
        public static void main(String[] args){
                Rodent1[] rodents = {
                                new Mouse1(),
                                new Gerbil1(),
                                new Hamster1(),
                };
                for(Rodent1 t:rodents){
                        t.bite();
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
//: polymorphism/Sandwich.java
// Order of constructor calls.
package exercises.Charpter9;
import static net.mindview.util.Print.*;

interface Fastfood {
        void bite();
}

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

public class Eight extends PortableLunch implements Fastfood{
  @SuppressWarnings("unused")
  private Bread b = new Bread();
  @SuppressWarnings("unused")
  private Cheese c = new Cheese();
  @SuppressWarnings("unused")
  private Lettuce l = new Lettuce();
  public Eight() { print("Sandwich()"); }
  
  public void bite (){
          System.out.println("Ouch! Who bite me?");
  }
          public static void main(String[] args) {
          Fastfood test = new Eight();
          test.bite();
          }
} /* Output:
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()
*///:~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
//: interfaces/music5/Music5.java
// Interfaces.
package exercises.Charpter9;
import polymorphism.music.Note;
import static net.mindview.util.Print.*;

interface Instrument {
  // Compile-time constant:
  int VALUE = 5; // static & final
  // Cannot have method definitions:
  void adjust();
}

class Wind implements Playable {
  public void play(Note n) {
    print(this + ".play() " + n);
  }
  public String toString() { return "Wind"; }
  public void adjust() { print(this + ".adjust()"); }
}

class Percussion implements Playable {
  public void play(Note n) {
    print(this + ".play() " + n);
  }
  public String toString() { return "Percussion"; }
  public void adjust() { print(this + ".adjust()"); }
}

class Stringed implements Playable {
  public void play(Note n) {
    print(this + ".play() " + n);
  }
  public String toString() { return "Stringed"; }
  public void adjust() { print(this + ".adjust()"); }
}

class Brass extends Wind {
  public String toString() { return "Brass"; }
}       

class Woodwind extends Wind {
  public String toString() { return "Woodwind"; }
}

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

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

import polymorphism.music.Note;

interface Playable extends Instrument{
          void play(Note n); // Automatically public
}

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

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

import interfaces.interfaceprocessor.Processor;

class TestAdapter{
        String reverse(String str){
                char[] charString = str.toCharArray();
                String ans = new String();
               
                for(int j = charString.length - 1; j >= 0; j--){
                        ans = ans + charString[j];
                }
                return ans.toString();
        }
}

class Adapter implements Processor{
        TestAdapter test;
        public Adapter(TestAdapter test){
                this.test = test;
        }
        @Override
        public String name(){
                return test.reverse("Test Reverse String!");
        }
        @Override
        public Object process(Object input) {
                return input;
        }
}

public class Eleven {
        public static void main(String[] args){
                Adapter test = new Adapter(new TestAdapter());
                System.out.println(test.name());
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

//: interfaces/Adventure.java
// Multiple interfaces.

interface CanFight {
  void fight();
}

interface CanSwim {
  void swim();
}

interface CanFly {
  void fly();
}

interface CanClimb{
        void climb();
}

class ActionCharacter {
  public void fight() {}
}       

class Hero extends ActionCharacter
    implements CanFight, CanSwim, CanFly ,CanClimb{
  public void swim() {}
  public void fly() {}
  public void climb() {}
}

public class Twelve {
        public static void t(CanFight x) { x.fight(); }
        public static void u(CanSwim x) { x.swim(); }
        public static void v(CanFly x) { x.fly(); }
        public static void w(ActionCharacter x) { x.fight(); }
        public static void c(CanClimb x) { x.climb(); }
        public static void main(String[] args) {
    Hero h = new Hero();
    t(h); // Treat it as a CanFight
    u(h); // Treat it as a CanSwim
    v(h); // Treat it as a CanFly
    w(h); // Treat it as an ActionCharacter
    c(h); // Treat it as a CanClimb
  }
} ///:~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

interface First{
        public void func1();
}

interface Second extends First{
        public void func2();
}

interface Third extends First{
        public void func3();
}

interface Fourth extends Second, Third{
        public void func4();
}

public class Thirteen {

}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

interface MyInterface extends Fourth{
        void newFunc();
}

class Myclass {
       
        public void func4() {
                System.out.println("classfunc4");
               
        }

       
        public void func2() {
                System.out.println("func2");
               
        }

       
        public void func1() {
                System.out.println("1func1");
               
        }

       
        public void func3() {
                System.out.println("func3");
               
        }

       
        public void newFunc() {
                System.out.println("newfunc");
               
        }

}

public class Fourteen extends Myclass implements MyInterface {

        public static void main(String[] args){
                MyInterface test = new Fourteen();
                ((MyInterface)test).func1();
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

abstract class MyAbstractClass{
        public void func1() {}
        public void func2() {}
        public void func3() {}
        public void func4() {}
}

public class Fifteen extends MyAbstractClass implements MyInterface{

        @Override
        public void newFunc() {
                System.out.println("~");
        }
       
        public static void main(String[] args){
                Fifteen testFifteen = new Fifteen();
                testFifteen.newFunc();
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Scanner;


class GenerateChar{
        public char[] gen(){
                char[] ans = {'1','2','3','4','5','6','7','8','9','0'};
                return ans;
        }
}

class AdaptedGenerateChar extends GenerateChar implements Readable{

        int i;
        public AdaptedGenerateChar(int i) {
                this.i = i;
        }

        @Override
        public int read(CharBuffer cb) throws IOException {
                if (this.i-- == 0)
                        return -1;
                for (char temp : super.gen()) {
                        cb.append(temp);
                }
                if (super.gen().length == 0)
                        return -1;
                return 0;
        }
}

public class Sixteen {
        public static void main(String[] args){
                Scanner s = new Scanner(new AdaptedGenerateChar(10));
                while (s.hasNext()) {
                        System.out.println(s.next());
                       
                }
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

interface TestField{
        int A = 1, B = 2;
}

public class Seventeen {
        public static void main(String[] args){
                System.out.println(TestField.A);
                System.out.println(TestField.B);
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

interface Cycle{
        void ride();
}

interface CycleFactory{
        Cycle getCycle ();
}

class Unicycle implements Cycle{

        @Override
        public void ride() {
                System.out.println("Unicycle ride");
        }
}

class UnicycleFactory implements CycleFactory{

        @Override
        public Cycle getCycle() {
                return new Unicycle();
        }
}

class Bicycle implements Cycle{
        @Override
        public void ride() {
                System.out.println("Bicycle ride");
        }
}

class BicycleFactory implements CycleFactory{

        @Override
        public Cycle getCycle() {
                return new Bicycle();
        }
}

class Tricycle implements Cycle{
        @Override
        public void ride() {
                System.out.println("Tricycle ride");
        }
}

class TricycleFactory implements CycleFactory{

        @Override
        public Cycle getCycle() {
                return new Tricycle();
        }
}

public class Eighteen {
        public static void ride(CycleFactory myFactory){
                Cycle myCycle = myFactory.getCycle();
                myCycle.ride();
        }
       
        public static void main(String[] args){
                ride(new UnicycleFactory());
                ride(new BicycleFactory());
                ride(new TricycleFactory());
        }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-6-4 00:30 | 显示全部楼层
package exercises.Charpter9;

import java.util.Random;

interface Gamble{
        Boolean win();
}

interface GambleFactory{
        Gamble getGamble();
}

class Coin implements Gamble{

        @Override
        public Boolean win() {
                Random rand = new Random();
                boolean win = rand.nextBoolean();
                return win;
        }
}

class CoinFactory implements GambleFactory{

        @Override
        public Gamble getGamble() {
                return new Coin();
        }
}

class Dice implements Gamble{

        @Override
        public Boolean win() {
                Random rand = new Random();
                boolean win = rand.nextBoolean();
                return win;
        }
}

class DiceFactory implements GambleFactory{

        @Override
        public Gamble getGamble() {
                return new Dice();
        }
}

public class Nineteen {
        public static void playGamble(Gamble myGamble){
                if (myGamble.win())
                        System.out.println("Win");
                else {
                        System.out.println("Lose");
                }
        }
       
        public static void main(String[] args){
                playGamble(new Coin());
                playGamble(new Dice());
        }
}
回复 支持 反对

使用道具 举报

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

GMT+8, 2023-11-30 02:27

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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