Java编程思想第四版第八章练习

断更了好几天,不过我胡汉三又回来了!

PS:编译环境:IDEA

1.创建一个Cycle类,它具有子类Unicycle,Bicycle和TriCycle.演示每一个类型的实例都可以经由ride()向上转型为Cycle。

package com.company;

class Cycle {
    public void ride(){
        System.out.println("ride of Cycle");
    }
}
class Unicycle extends Cycle{
    public void ride(){
        System.out.println("ride of Uncycyle");
    }
}
class Bicycle extends Cycle{
    public void ride(){
        System.out.println("ride of Bicycle");
    }
}
class Tricycle extends Cycle{
    public void ride(){
        System.out.println("ride of Tricycle");
    }
}
public class Main {

    public static void run(Cycle a) {
        a.ride();
    }

    public static void main(String[] args) {
        Unicycle a = new Unicycle();
        Bicycle b = new Bicycle();
        Tricycle c = new Tricycle();
        run(a);
        run(b);
        run(c);
    }
}

 output:

ride of Uncycyle
ride of Bicycle
ride of Tricycle

2.在几何图形的示例中添加@Override注解。

package job;

import java.util.*;

class Shape {

    public void draw() {
    }

    public void erase() {
    }

}

class Square extends Shape {

    @Override
    public void draw() {
        System.out.println("Square.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Square.erase()");
    }

}



class Triangle extends Shape {

    @Override
    public void draw() {
        System.out.println("Triangle.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Triangle.erase()");
    }

}

class Circle extends Shape {

    @Override
    public void draw() {
        System.out.println("Circle.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Circle.erase()");
    }

}

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 Main {

    private static RandomShapeGenerator gen =

            new RandomShapeGenerator();

    public static void main(String[] args) {

        Shape[] s = new Shape[9];

        // Fill up the array with shapes:

        for (int i = 0; i < s.length; i++)

            s[i] = gen.next();

        // Make polymorphic method calls:

        for (Shape shp : s)

            shp.draw();

    }

}

3.在基类Shape().java中添加一个新方法,用于打印一条消息,但导出类中不要覆盖这个方法。请解释发生了什么。现在,在其中一个导出类中覆盖该方法,而在其他的导出类不予覆盖,观察又有什么发生。最后,在所有的导出类中覆盖这个方法。

package job;

import java.util.*;

class Shape {

    public void draw() {
    }

    public void erase() {
    }
    public void show(){
        System.out.println("Shape");
    }
}

class Square extends Shape {

    @Override
    public void draw() {
        System.out.println("Square.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Square.erase()");
    }

}



class Triangle extends Shape {

    @Override
    public void draw() {
        System.out.println("Triangle.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Triangle.erase()");
    }

}

class Circle extends Shape {

    @Override
    public void draw() {
        System.out.println("Circle.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Circle.erase()");
    }

}

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 Main {

    private static RandomShapeGenerator gen =

            new RandomShapeGenerator();

    public static void main(String[] args) {

        Shape[] s = new Shape[9];

        // Fill up the array with shapes:

        for (int i = 0; i < s.length; i++)

            s[i] = gen.next();

        // Make polymorphic method calls:

        for (Shape shp : s) {

            //shp.draw();
            shp.show();
        }

    }

}

output:

Shape
Shape
Shape
Shape
Shape
Shape
Shape
Shape
Shape
 

package job;

import java.util.*;

class Shape {

    public void draw() {
    }

    public void erase() {
    }

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

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 show(){
        System.out.println("Square");
    }
}



class Triangle extends Shape {

    @Override
    public void draw() {
        System.out.println("Triangle.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Triangle.erase()");
    }

}

class Circle extends Shape {

    @Override
    public void draw() {
        System.out.println("Circle.draw()");
    }

    @Override
    public void erase() {
        System.out.println("Circle.erase()");
    }

}

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 Main {

    private static RandomShapeGenerator gen =

            new RandomShapeGenerator();

    public static void main(String[] args) {

        Shape[] s = new Shape[9];

        // Fill up the array with shapes:

        for (int i = 0; i < s.length; i++)

            s[i] = gen.next();

        // Make polymorphic method calls:

        for (Shape shp : s) {

            //shp.draw();
            shp.show();
        }

    }

}

output:

Shape
Shape
Square
Shape
Square
Shape
Square
Shape
Shape

package job;

import java.util.*;

class Shape {

    public void draw() {
    }

    public void erase() {
    }

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

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 show(){
        System.out.println("Square");
    }
}



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 show() {
        System.out.println("Triangle");
    }
}

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 show() {
        System.out.println("Circle");
    }
}

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 Main {

    private static RandomShapeGenerator gen =

            new RandomShapeGenerator();

    public static void main(String[] args) {

        Shape[] s = new Shape[9];

        // Fill up the array with shapes:

        for (int i = 0; i < s.length; i++)

            s[i] = gen.next();

        // Make polymorphic method calls:

        for (Shape shp : s) {

            //shp.draw();
            shp.show();
        }

    }

}

output:

Triangle
Triangle
Square
Triangle
Square
Triangle
Square
Triangle
Circle

4.向Shape.java中添加一个新的Shape类型,并在main()方法中验证:多态对新类型的作用是否与在旧类型中的一样。

package job;

import java.util.*;

class Shape {

    public void draw() {
    }

    public void erase() {
    }

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

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 show(){
        System.out.println("Square");
    }
}



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 show() {
        System.out.println("Triangle");
    }
}

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 show() {
        System.out.println("Circle");
    }
}
class PP extends Shape {
    @Override
    public void draw() {
        System.out.println("PP.draw()");
    }

    @Override
    public void erase() {
        System.out.println("PP.erase()");
    }

    @Override
    public void show() {
        System.out.println("PP");
    }
}

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 Main {

    private static RandomShapeGenerator gen =

            new RandomShapeGenerator();

    public static void main(String[] args) {

//        Shape[] s = new Shape[9];
//
//        // Fill up the array with shapes:
//
//        for (int i = 0; i < s.length; i++)
//
//            s[i] = gen.next();
//
//        // Make polymorphic method calls:
//
//        for (Shape shp : s) {
//
//            //shp.draw();
//            shp.show();
//        }
        PP p=new PP();
        p.draw();//输出的是p类重写的方法,证明多态对新类的作用与在旧类中是一样的
        p.show();
        p.erase();
    }

}

 output:

PP.draw()
PP
PP.erase()

5.以练习1为基础,在Cycle中添加wheels()方法,它将返回轮子的数量。修改ride()方法,让它调用wheels()方法,并验证多态起作用了。

package job;

class Cycle {
    public void ride(){
        System.out.println("ride of Cycle");
        wheels();
    }
    public void wheels(){
        System.out.println("轮胎数为:0");
    }
}
class Unicycle extends Cycle{
    public void ride(){
        System.out.println("ride of Uncycyle");
        wheels();
    }
    public void wheels(){
        System.out.println("轮胎数为:1");
    }
}
class Bicycle extends Cycle{
    public void ride(){
        System.out.println("ride of Bicycle");
        wheels();
    }
    public void wheels(){
        System.out.println("轮胎数为:2");
    }
}
class Tricycle extends Cycle{
    public void ride(){
        System.out.println("ride of Tricycle");
        wheels();
    }
    public void wheels(){
        System.out.println("轮胎数为:3");
    }
}
public class Main {

    public static void run(Cycle a) {
        a.ride();
    }

    public static void main(String[] args) {
        Unicycle a = new Unicycle();
        Bicycle b = new Bicycle();
        Tricycle c = new Tricycle();
        run(a);
        run(b);
        run(c);
    }
}

output:

ride of Uncycyle
轮胎数为:1
ride of Bicycle
轮胎数为:2
ride of Tricycle
轮胎数为:3

PS:我觉得我这个方法很明显的验证了多态起作用!给我自己点个赞。

6.修改Music3.java,使what()方法成为根Object的toString方法.试用System.out.Printfln()方法打印Instrucment对象(不用向上转型)

 

package job;
import java.util.*;
enum Note{
    MIDDLE_C,C_SHARP,B_FLAT;
}
class Instrument {
    void play(Note n) { System.out.println("Instrument.play() " + n); }
    public String what() {
        return "Instrument";
    }
    public String toString(){
        return what();
    }
    void adjust() { System.out.println("Adjusting Instrument"); }
}

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

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

class Stringed extends Instrument {
    void play(Note n) { System.out.println("Stringed.play() " + n); }
    public String what() {
        return "Stringed";
    }

    void adjust() { System.out.println("Adjusting Stringed"); }
}

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

class Woodwind extends Wind {
    void play(Note n) {System.out.println("Woodwind.play() " + n); }

    public String what() {
        return "Woodwind";
    }
    public String toString(){
        return what();
    }
}

public class Main {
    // 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);
            System.out.println(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);
    }
}

output:

Wind.play() MIDDLE_C
Wind
Percussion.play() MIDDLE_C
Percussion
Stringed.play() MIDDLE_C
Stringed
Brass.play() MIDDLE_C
Wind
Woodwind.play() MIDDLE_C
Woodwind

PS:这里补充一下之前没有提到过的,String toSting() 这个函数,是用来把对象转化为String类型的。

7.想Music3.java添加一个新的类型Instrument,并验证多态性是否作用于所添加的新类型。

 

package job;
import java.util.*;
enum Note{
    MIDDLE_C,C_SHARP,B_FLAT;
}
class Instrument {
    void play(Note n) { System.out.println("Instrument.play() " + n); }
    public String what() {
        return "Instrument";
    }
    public String toString(){
        return what();
    }
    void adjust() { System.out.println("Adjusting Instrument"); }
}

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

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

class Stringed extends Instrument {
    void play(Note n) { System.out.println("Stringed.play() " + n); }
    public String what() {
        return "Stringed";
    }

    void adjust() { System.out.println("Adjusting Stringed"); }
}

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

class Woodwind extends Wind {
    void play(Note n) {System.out.println("Woodwind.play() " + n); }

    public String what() {
        return "Woodwind";
    }
    public String toString(){
        return what();
    }
}

class guitar extends Instrument{
    @Override
    public void play(Note n){
        System.out.println("guitar.play()"+n);
    }
}
public class Main {
    // 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);
            System.out.println(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 guitar()
        };
        tuneAll(orchestra);
        guitar x=new guitar();
        x.play(Note.B_FLAT);
    }
}

output:

Wind.play() MIDDLE_C
Wind
Percussion.play() MIDDLE_C
Percussion
Stringed.play() MIDDLE_C
Stringed
Brass.play() MIDDLE_C
Wind
Woodwind.play() MIDDLE_C
Woodwind
guitar.play()MIDDLE_C
Instrument
guitar.play()B_FLAT 

8.修改Music3.java,使其可以像Shapes.java中的方式那样可以随机创建Instrument对象

package job;
import java.util.*;
enum Note{
    MIDDLE_C,C_SHARP,B_FLAT;
}
class Instrument {
    void play(Note n) { System.out.println("Instrument.play() " + n); }
    public String what() {
        return "Instrument";
    }
    public String toString(){
        return what();
    }
    void adjust() { System.out.println("Adjusting Instrument"); }
}

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

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

class Stringed extends Instrument {
    void play(Note n) { System.out.println("Stringed.play() " + n); }
    public String what() {
        return "Stringed";
    }

    void adjust() { System.out.println("Adjusting Stringed"); }
}

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

class Woodwind extends Wind {
    void play(Note n) {System.out.println("Woodwind.play() " + n); }

    public String what() {
        return "Woodwind";
    }
    public String toString(){
        return what();
    }
}

class guitar extends Instrument{
    @Override
    public void play(Note n){
        System.out.println("guitar.play()"+n);
    }
}
public class Main {
    // Doesn't care about type, so new types
    // added to the system still work right:
    static Random rand=new Random();
    public static void tune(Instrument i) {
        // ...
        i.play(Note.MIDDLE_C);
    }
    public static void tuneAll(Instrument[] e) {
        for(Instrument i : e) {
            tune(i);
            System.out.println(i);
        }
    }
    public static Instrument back(){
      while(true) {
          switch (rand.nextInt(6)) {
              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 guitar();
              default:
          }
      }
    }
    public static void main(String[] args) {
        // Upcasting during addition to the array:
        Instrument[] orchestra = {
                back(),
                back(),
                back(),
        };
        tuneAll(orchestra);
    }
}

 PS:

这里有一个小插曲,back函数原来我是这么写的,但是会报错,因为我遗忘了case 0,为了弥补过错,我加了个break a

    public static Instrument back(){
      a:
      {
          switch (rand.nextInt(6)) {
              case 6:
                  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 guitar();
              default:
                  break a;
          }
      }
      return null;
    }

很愚蠢,break a是跳出a的块,没有达成我想继续switch的效果,最后想到了while死循环,才能完成这道题 。

查阅资料网址:https://stackoverflow.com/questions/28003929/break-label-in-switch

关键句子:

9.创建Rodent(啮齿动物):Mnouse(老鼠),Gerbil(鼹鼠),Hamster(大颊鼠),等等这样一个的继承层次结构。在基类中,提供对所有的Rodent都通用的方法,在导出类中,根据特定的Rodent类型覆盖这些方法,以便它们执行不同的行为。创建一个Robent数组,填充不同的Rodent类型,然后调用基类方法,观察发生什么情况。

 

package job;
import java.awt.*;
import java.util.*;
class Rodent{
    void bit(){};
}
class Mouse extends Rodent{
    @Override
    void bit(){
        System.out.println("Mouse bit");
    }
}
class Gerbil extends Rodent{
    @Override
    void bit(){
        System.out.println("Gerbil bit");
    }
}
class Hamster extends Rodent{
    @Override
    void bit(){
        System.out.println("Hamster bit");
    }
}
public class Main {
    public static void main(String[] args) {
        Rodent[] a= {
                new Mouse(),
                new Gerbil(),
                new Hamster(),
        };
        for(Rodent e:a){
            e.bit();
        }
    }
}

outPut:

Mouse bit
Gerbil bit
Hamster bit 

10.创建一个包含两个方法的基类。在第一个方法中可以调用第二个方法。然后产生一个继承自该基类的导出类,且覆盖基类中的第二个方法。为该导出类创建一个对象,将他向上转型到基类并调用第一个方法,解释发生的情况。

package job;
import java.awt.*;
import java.util.*;
class A{
    void show(){
        System.out.println("showing A");
        show2();
    }
    void show2(){
        System.out.println("Showing A2");
    }
}
class B extends A {
    @Override
    void show2() {
        System.out.println("Showing B");
    }
}
public class Main {
    public static void main(String[] args) {
        B b=new B();
        b.show();
    }
}

output:

showing A
Showing B

11.向Sandwich.java中添加Pickle类。

 太简单了 略

12.修改练习(9),使其能够演示基类和导出类的初始化顺序。然后向基类和导出类中添加成员对象,并说明构建期间初始化发生的顺序。

 

package job;
import java.awt.*;
import java.util.*;
class Rodent{
    private String s="aaaa";
    Rodent(){
        System.out.println(s);
        System.out.println("Rodent creating");
    }
    void bit(){};
}
class Mouse extends Rodent{
    private String s="bbbbb";
    @Override
    void bit(){
        System.out.println("Mouse bit");
    }
    Mouse(){
        System.out.println(s);
        System.out.println("Mouse creating");
    }
}
class Gerbil extends Rodent{
    private String s="ccccc";
    @Override
    void bit(){
        System.out.println("Gerbil bit");
    }
    Gerbil(){
        System.out.println(s);
        System.out.println("Gerbil creating");
    }
}
class Hamster extends Rodent{
    private String s="ddddd";
    @Override
    void bit(){
        System.out.println("Hamster bit");
    }
    Hamster(){
        System.out.println(s);
        System.out.println("Hamster creating");
    }
}
public class Main {
    public static void main(String[] args) {
        Rodent[] a= {
                new Mouse(),
                new Gerbil(),
                new Hamster(),
        };
    }
}

output:

aaaa
Rodent creating
bbbbb
Mouse creating
aaaa
Rodent creating
ccccc
Gerbil creating
aaaa
Rodent creating
ddddd
Hamster creating
13.在ReferenceCounting.java中添加一个finalized()方法,用来校验终止条件。

package job;
import java.util.*;
class Shared {

    private int refcount = 0;

    private static long counter = 0;

    private final long id = counter++;

    public Shared() {

        System.out.println("Creating " + this);

    }

    public void addRef() {
        refcount++;
    }

    protected void dispose() {

        if (--refcount == 0)

            System.out.println("Disposing " + this);

    }

    public String toString() {
        return "Shared " + id;
    }

}



class Composing {

    private Shared shared;

    private static long counter = 0;

    private final long id = counter++;

    public Composing(Shared shared) {

        System.out.println("Creating " + this);

        this.shared = shared;

        this.shared.addRef();

    }

    protected void dispose() {

        System.out.println("disposing " + this);

        shared.dispose();

    }

    public String toString() {
        return "Composing " + id;
    }

}



public class Main {

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

    }

}

 14.修改练习12,使其某个成员对象变为具有引用计数的共享对象,并证明它可以正常运行。

 


package job;
import java.util.*;

public class Main {

    public static void main(String[] args) {

        Mouse m = new Mouse();

        Gerbil[] gb = {new Gerbil(m), new Gerbil(m), new Gerbil(m), new Gerbil(m),};

        for (Gerbil g : gb) {
            g.dispose();
        }

    }

}

class Rodent {

    //private int k=printInit("in Rodent's data.");

    //public Rodent(){System.out.println("I am 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 Rodent");
    }

    public String toString() {
        return "Eodent";
    }

    static int printInit(String s) {

        System.out.println(s);

        return 47;

    }

}

class Mouse extends Rodent {

    private static int refcount = 0;

    private static int count = 0;

    private final int id = count++;

    public void refAdd() {
        refcount++;
    }

    protected void dispose() {
        if (--refcount == 0) System.out.println("Disposing " + this);
    }

    public String toString() {
        return "Mouse " + id;
    }

    //private int k=printInit("in Mouse's data.");

    public Mouse() {
        System.out.println("Creating " + this);
    }


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

}

class Gerbil extends Rodent {

    private static int count = 0;

    private final int id = count++;

    private Mouse m;

    public String toString() {
        return "Gerbil " + id;
    }

    public Gerbil(Mouse m) {
        this.m = m;
        m.refAdd();
        System.out.println("Creating " + this);
    }

    protected void dispose() {
        System.out.println("Disposing " + this);
        m.dispose();
    }


    public void hop() {
        System.out.println("Gerbil hopping");
    }

    public void scurry() {
        System.out.println("Gerbil scurrying");
    }

    public void reproduce() {
        System.out.println("Making more 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 Hamster");
    }

    public String toString() {
        return "Hamster";
    }

}

15.在PolyConstructors.java中添加一个RectangularGlyph,并证明会出现本节所描述的问题。


package job;
import java.util.*;


class Glyph {

    void draw() {
        System.out.println("Glyph.draw()");
    }

    Glyph() {

        System.out.println("Glyph() before draw()");

        draw();

        System.out.println("Glyph() after draw()");

    }

}



class RoundGlyph extends Glyph {

    private int radius = 1;

    RoundGlyph() {
        System.out.println("Before RoundGlyph");
        draw();
        System.out.println("After RoundGlyph");
    }

    void draw() {
        System.out.println("RoundGlyph.draw(), radius = " + radius);
    }

}



class RectangularGlyph extends RoundGlyph {

    private int rg = 5;

    public RectangularGlyph() {

        System.out.println("RectangularGlyph.RectangularGlyph(),rg= " + rg);

    }

    void draw() {
        System.out.println("RectangularGlyph.draw(),rg=" + rg);
    }

}



public class Main {

    public static void main(String[] args) {

        new RectangularGlyph();

    }

}

 output:

Glyph() before draw()
RectangularGlyph.draw(),rg=0
Glyph() after draw()
Before RoundGlyph
RectangularGlyph.draw(),rg=0
After RoundGlyph
RectangularGlyph.RectangularGlyph(),rg= 5

16.遵循Transmogrify.java这个例子,创建一个Starship类,包含一个AlertStatus引用,此引用可以指示三种不同的状态。纳入一些可以改变这些状态的方法。


package job;

class GoodShip extends Ship {
    public void act(){
        System.out.println("GOODNESS");
    }
}
class FamilyShip extends Ship {
    public void act(){
        System.out.println("family");
    }
}
class Friengship extends Ship {
    public void act(){
        System.out.println("friend");
    }
}
class Ship {
    public void act(){}
}
class Starship{
    private Ship S=new GoodShip();
    void AlertStatus(){
        switch (0){
            case 0:S=new GoodShip();
            case 1:S=new FamilyShip();
            case 2:S=new Friengship();
        }
    }
    void showShip(){
        S.act();
    }
}
public class Main {

    public static void main(String[] args) {

        Starship a=new Starship();
        a.AlertStatus();
        a.showShip();

    }

}

 output:

friend

17.使用练习1中的Cycle的层次结构,在Unicycle 和Bicycle中添加balance方法,而Tricycle中不添加。创建这三种类型的实例,并将他们向上转型为Cycle数组。在该数组的每一个元素上都尝试调用balance,并观察结果。然后将他们向下转型,再次调用balance(),并观察将所发生什么。

package job;

class Cycle {
    public void balance(){
        System.out.println("Cycle balancing");
    }
}
class Unicycle extends Cycle{
    public void balance(){
        System.out.println("Unicycle balancing");
    }
}
class Bicycle extends Cycle{
    public void balance(){
        System.out.println("Bicycle balancing");
    }
}
class Tricycle extends Cycle{
}
public class Main {
    public static void main(String[] args) {
        Cycle[] a= {
                new Unicycle(),
                new Bicycle(),
                new Tricycle(),
                new Cycle()
        };
       for(Cycle e:a){
           e.balance();
       }
        //((Bicycle)a[0]).balance();//class job.Unicycle cannot be cast to class job.Bicycle
        ((Bicycle)a[1]).balance();
        ((Tricycle)a[2]).balance();
        ((Cycle)a[3]).balance();
    }
}

 output:

Unicycle balancing
Bicycle balancing
Cycle balancing
Cycle balancing
Bicycle balancing
Cycle balancing
Cycle balancing

PS:向下转型个人感觉就是个强转...

结束~
我的另一个博客:https://www.cnblogs.com/hsjj/
会不定时的更新算法题
有问题欢迎发送邮件至[email protected]
我们下次见哦~

你可能感兴趣的:(JAVA,Java编程思想第四版答案)