java编程思想第四版第九章习题

简介: 输出结果: 调用基类构造方法的时候, 只是给子类的成员变量分配了一块内存空间, 并将内存空间的值设置为默认值0.

1.第三题


package net.mindview.interfaces;
abstract class Base{
    public Base(){
        print();
    }
    abstract void print();
}
public class Test3 extends Base{
    private int i = 5;
    @Override
    void print() {
        System.out.println(i);
    }
    public static void main(String[] args) {
        Test3 t = new Test3();
        t.print();
    }
}


输出结果:


0
5


调用基类构造方法的时候, 只是给子类的成员变量分配了一块内存空间, 并将内存空间的值设置为默认值0. 当真正调用子类构造方法之前才会为成员变量赋值.


2.第七题


package net.mindview.interfaces;
//啮(nie四声)齿动物
interface Rodent{
  void say();
}
//老鼠
class Mouse implements Rodent{
  public void say(){System.out.println("hi,我是 Mouse");}
}
//鼹鼠
class Gerbil implements Rodent{
  public void say(){System.out.println("hi,我是 Gerbil");}
}
//大颊鼠
class Hamster implements Rodent{
  public void say(){System.out.println("hi,我是 Hamster");}
}
public class RodentHome {
    public static void instroduce(Rodent rodent){
        rodent.say();
    }
    public static void instroduceAll(Rodent[] rodents){
        for(Rodent r: rodents){
            instroduce(r);
        }
    }
    public static void main(String[] args) {
        Rodent[] rodents = {
                new Mouse(),
                new Gerbil(),
                new Hamster()
        };
        instroduceAll(rodents);
    }
}


3.第八题


package net.mindview.interfaces;
import java.util.Random;
/** 定义一个乐器类 */
interface Instrucment {
    int value = 5; //定义在接口中的成员是static&final的
    void play(Note n);
    void adjust();
}
/**抽象类*/
abstract class PublicMethod implements Instrucment{
    public abstract void play(Note n);
    //这个方法不用谢,以为继承自Object的类都有toString()方法
    //public abstract String toString();
    public abstract void adjust();
}
/**定义n个子类*/
class Wind extends PublicMethod {
    public void play(Note n){ System.out.println("Wind.play() " + n);}
    public String toString(){ return "Wind.what()";}
    public void adjust(){ System.out.println("Wind.adjust()");}
}
class Purcussion extends PublicMethod{
    public void play(Note n){ System.out.println("Purcussion.play() " + n);}
    public String toString(){ return "Purcussion.what()";}
    public void adjust(){ System.out.println("Purcussion.adjust()");}
}
class Stringed extends PublicMethod{
    public void play(Note n){ System.out.println("Stringed.play() " + n);}
    public String toString(){ return "Stringed.what()";}
    public void adjust(){ System.out.println("Stringed.adjust()");}
}
class Brass extends Wind{
    public void play(Note n){ System.out.println("Brass.play() " + n);}
    public void adjust(){ System.out.println("Brass.adjust()");}
}
class WoodWind extends Wind{
    public void play(Note n){ System.out.println("WoodWind.play() " + n);}
    public String toString(){ return "WoodWind.what()";}
}
class Other extends Wind{
    public void play(Note n){ System.out.println("Other.play() " + n);}
    public String toString(){ return "Other.what()";}
}
/** 定义一个随机乐器生成器 */
class RandomInstrucmentGenerator {
    Random rand = new Random(100);
    public Instrucment next(){
        switch(rand.nextInt(6)){
            default:
            case 0: return new Wind();
            case 1: return new Purcussion();
            case 2: return new Stringed();
            case 3: return new Brass();
            case 4: return new WoodWind();
            case 5: return new Other();
        }
    }
}
public class Music5 {
    public static void tune(Instrucment i){
        i.play(Note.MIDDLE_C);
        i.toString();
    }
    public static void tuneAll(Instrucment[] e){
        for(Instrucment i : e){
            tune(i);
        }
    }
    private static RandomInstrucmentGenerator gen = new RandomInstrucmentGenerator();
    public static void main(String[] args) {
        /*Instrucment[] orchestra = {
            new Wind(),
            new Purcussion(),
            new Stringed(),
            new Brass(),
            new WoodWind(),
            new Other()
        };*/
        Instrucment[] ins = new Instrucment[10];
        for(int i=0; i<ins.length; i++){
            ins[i] = Music5.gen.next();
        }
        tuneAll(ins);
    }
}


4.练习11--这个练习是巩固如何写适配器设计模式


package net.mindview.interfaces;
/**
 * 字符串反转类
 */
public class StringReverse {
    public String name(){
        return getClass().getSimpleName();
    }
    //反转
    public String reverse(String s) {
        char[] array = s.toCharArray();
        String reverse = "";
        for (int i = array.length - 1; i >= 0; i--) {
            reverse += array[i];
        }
        return reverse;
    }
}


package net.mindview.interfaces;
public class StringReverseAdapter implements Processor{
    StringReverse stringReverse;
    public StringReverseAdapter(StringReverse stringReverse){
        this.stringReverse = stringReverse;
    }
    @Override
    public String name() {
        // TODO Auto-generated method stub
        return stringReverse.name();
    }
    @Override
    public Object process(Object input) {
        // TODO Auto-generated method stub
        return stringReverse.reverse((String)input);
    }
}


在使用的时候,可以直接调用Apply的process方法


public static void main(String[] args) {
        Apply.process(new StringReverseAdapter(new StringReverse()), "i am lily");
    }


Apply方法没有写出来,这个类实在课文内部定义的,可以参考http://www.cnblogs.com/ITPower/p/8550627.html中第二点:解耦的案例一,案例二和案例三. 其中Apply类定义在案例一中。


5.第十二题


package net.mindview.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{
    @Override
    public void fly() { }
    @Override
    public void swim() { }
    @Override
    public void climb() { }
} 
//冒险
public class Adventure {
    public static void f(CanFly fly){
        fly.fly();
    }
    public static void s(CanSwim swim){
        swim.swim();
    }
    public static void v(CanFight fight){
        fight.fight();
    }
    public static void m(ActionCharacter ac){
        ac.fight();
    }
    public static void p(CanClimb c){
        c.climb();
    }
    public static void main(String[] args) {
        Hero hero = new Hero();
        f(hero);
        s(hero);
        v(hero);
        m(hero);
        p(hero);
    }
}


6.第十四题:这道题的思想和书上p180页的案例思想一样.继承+多次实现接口


package net.mindview.interfaces;
interface BaseInterface1 {
    public void a();
    public void b();
}
interface BaseInterface2 {
    public void c();
    public void d();
}
interface BaseInterface3 {
    public void e();
    public void f();
}
interface Interface4 extends BaseInterface1,BaseInterface2,BaseInterface3{
    public void g();
}
class Specific implements Interface4{
    public void h(){ }
    @Override
    public void a() { }
    @Override
    public void b() { }
    @Override
    public void c() { }
    @Override
    public void d() { }
    @Override
    public void e() { }
    @Override
    public void f() { }
    @Override
    public void g() { }
}
public class Test14 extends Specific implements Interface4{
    public static void aa(BaseInterface1 b1){
        b1.a();
        b1.b();
    }
    public static void bb(BaseInterface2 b){
        b.c();
        b.d();
    }
    public static void cc(BaseInterface3 b){
        b.e();
        b.f();
    }
    public static void dd(Interface4 b){
        b.g();
    }
    public static void main(String[] args) {
        Specific specific = new Specific();
        aa(specific);
        bb(specific);
        cc(specific);
        dd(specific);
    }
}


7.第十六题


package net.mindview.interfaces;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Random;
import java.util.Scanner;
class RandomChar {
    Random rand = new Random(47);
    Random count = new Random(47);
    private static final char[] captials = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); 
    public char[] make(){
        StringBuffer sb = new StringBuffer("");
        for(int i=0; i<count.nextInt(10); i++){
            sb.append(captials[rand.nextInt(captials.length)]);
        }
        return sb.toString().toCharArray();
    }
    public static void main(String[] args) {
        RandomChar rc = new RandomChar();
        char[] c = rc.make();
        System.out.println(c);
        for(char ch:c){
            System.out.print(ch);
        }
    }
}
public class AdapterRandomChar implements Readable{
    RandomChar rc;
    private int count;
    public AdapterRandomChar(RandomChar rc, int count){
        this.rc = rc;
        this.count = count;
    }
    @Override
    public int read(CharBuffer cb) throws IOException {
        if(count-- == 0){
            return -1;
        }
        StringBuffer sb = new StringBuffer("");
        for(char c:rc.make()){
            sb.append(c);
        }
        String result = sb.toString() + " " ;
        cb.append(result);
        return result.length();
    }
    public static void main(String[] args) {
        Scanner s = new Scanner(new AdapterRandomChar(new RandomChar(), 5));
        while(s.hasNext()){
            System.out.print(s.next()+" ");
        }
    }
}


8.第十八题


package net.mindview.interfaces;
//产品
interface Cycle {
}
class Unicycle implements Cycle{
    public Unicycle(){
        System.out.println("我是一个Unicycle");
    }
}
class Bicycle implements Cycle{
    public Bicycle(){
        System.out.println("我是一个Bicycle");
    }
}
class Tricycle implements Cycle{
    public Tricycle(){
        System.out.println("我是一个Tricycle");
    }
}
//工厂类
interface CycleFactory{
    public Cycle make();
}
class UnicycleFactory implements CycleFactory{
    @Override
    public Cycle make() {
        return new Unicycle();
    }
}
class BicycleFactory implements CycleFactory{
    @Override
    public Cycle make() {
        return new Bicycle();
    }
}
class TricycleFactory implements CycleFactory{
    @Override
    public Cycle make() {
        return new Tricycle();
    }
}
public class CycleCustomer {
    public static Cycle serviceCustoemr(CycleFactory fact){
        return fact.make();
    }
    public static void main(String[] args) {
        Cycle u = serviceCustoemr(new UnicycleFactory());
        Cycle b = serviceCustoemr(new BicycleFactory());
        Cycle t = serviceCustoemr(new TricycleFactory());
    }
}


9.第十九题


package net.mindview.interfaces;
import java.util.Random;
/**
 * 这时一个抛硬币和掷骰子等类型的框架
 */
interface ThrowProduct {}
class ThrowCorn implements ThrowProduct{
    Random rand = new Random(47);
    public ThrowCorn(){
        if(rand.nextInt(100) %2 ==0){
            System.out.println("硬币的正面");
        }else{
            System.out.println("硬币的反面");
        }
    }
}
class ThrowDice implements ThrowProduct{
    Random rand = new Random(47);
    public ThrowDice(){
        System.out.println("掷的骰子数是"+rand.nextInt(7));
    }
}
interface ThrowFactory{
    ThrowProduct throwOut();
}
class ThrowCornFactory implements ThrowFactory{
    public ThrowCornFactory(){
        System.out.print("开始抛硬币:");
    }
    @Override
    public ThrowProduct throwOut() {
        return new ThrowCorn();
    }
}
class ThrowDiceFactory implements ThrowFactory{
    public ThrowDiceFactory(){
        System.out.print("开始掷骰子:");
    }
    @Override
    public ThrowProduct throwOut() {
        return new ThrowDice();
    }
}
public class ThrowFrame {
    public static ThrowProduct service(ThrowFactory f){
        return f.throwOut();
    }
    public static void main(String[] args) {
        service(new ThrowCornFactory());
        service(new ThrowDiceFactory());
    }
}


结果:


开始抛硬币:硬币的正面
开始掷骰子:掷的骰子数是6
相关文章
|
1天前
|
存储 Java
JAVA并发编程AQS原理剖析
很多小朋友面试时候,面试官考察并发编程部分,都会被问:说一下AQS原理。面对并发编程基础和面试经验,专栏采用通俗简洁无废话无八股文方式,已陆续梳理分享了《一文看懂全部锁机制》、《JUC包之CAS原理》、《volatile核心原理》、《synchronized全能王的原理》,希望可以帮到大家巩固相关核心技术原理。今天我们聊聊AQS....
|
1天前
|
Java 程序员 数据库连接
Java编程中的异常处理:从基础到进阶
【9月更文挑战第18天】在Java的世界里,异常处理是每个程序员必须面对的挑战。本文将带你从异常的基本概念出发,通过实际的代码示例,深入探讨如何有效地管理和处理异常。我们将一起学习如何使用try-catch块来捕捉异常,理解finally块的重要性,以及如何自定义异常类来满足特定需求。无论你是初学者还是有经验的开发者,这篇文章都将为你提供新的见解和技巧,让你的Java代码更加健壮和可靠。
|
1天前
|
Java 数据库连接 UED
掌握Java编程中的异常处理
【9月更文挑战第18天】在Java的世界中,异常是那些不请自来的客人,它们可能在任何时候突然造访。本文将带你走进Java的异常处理机制,学习如何优雅地应对这些突如其来的“访客”。从基本的try-catch语句到更复杂的自定义异常,我们将一步步深入,确保你能够在面对异常时,不仅能够从容应对,还能从中学到宝贵的经验。让我们一起探索如何在Java代码中实现健壮的异常处理策略,保证程序的稳定运行。
|
2天前
|
Java 数据库
JAVA并发编程-一文看懂全部锁机制
曾几何时,面试官问:java都有哪些锁?小白,一脸无辜:用过的有synchronized,其他不清楚。面试官:回去等通知! 今天我们庖丁解牛说说,各种锁有什么区别、什么场景可以用,通俗直白的分析,让小白再也不怕面试官八股文拷打。
|
8天前
|
缓存 Java 编译器
JAVA并发编程volatile核心原理
volatile是轻量级的并发解决方案,volatile修饰的变量,在多线程并发读写场景下,可以保证变量的可见性和有序性,具体是如何实现可见性和有序性。以及volatile缺点是什么?
|
2天前
|
Java
深入理解Java中的多线程编程
本文将探讨Java多线程编程的核心概念和技术,包括线程的创建与管理、同步机制以及并发工具类的应用。我们将通过实例分析,帮助读者更好地理解和应用Java多线程编程,提高程序的性能和响应能力。
15 4
|
10天前
|
Java 调度 开发者
Java并发编程:深入理解线程池
在Java的世界中,线程池是提升应用性能、实现高效并发处理的关键工具。本文将深入浅出地介绍线程池的核心概念、工作原理以及如何在实际应用中有效利用线程池来优化资源管理和任务调度。通过本文的学习,读者能够掌握线程池的基本使用技巧,并理解其背后的设计哲学。
|
2天前
|
安全 Java 开发者
Java并发编程中的锁机制解析
本文深入探讨了Java中用于管理多线程同步的关键工具——锁机制。通过分析synchronized关键字和ReentrantLock类等核心概念,揭示了它们在构建线程安全应用中的重要性。同时,文章还讨论了锁机制的高级特性,如公平性、类锁和对象锁的区别,以及锁的优化技术如锁粗化和锁消除。此外,指出了在高并发环境下锁竞争可能导致的问题,并提出了减少锁持有时间和使用无锁编程等策略来优化性能的建议。最后,强调了理解和正确使用Java锁机制对于开发高效、可靠并发应用程序的重要性。
11 3
|
1天前
|
安全 Java 调度
Java 并发编程中的线程安全和性能优化
本文将深入探讨Java并发编程中的关键概念,包括线程安全、同步机制以及性能优化。我们将从基础入手,逐步解析高级技术,并通过实例展示如何在实际开发中应用这些知识。阅读完本文后,读者将对如何在多线程环境中编写高效且安全的Java代码有一个全面的了解。
|
2天前
|
安全 Java API
JAVA并发编程JUC包之CAS原理
在JDK 1.5之后,Java API引入了`java.util.concurrent`包(简称JUC包),提供了多种并发工具类,如原子类`AtomicXX`、线程池`Executors`、信号量`Semaphore`、阻塞队列等。这些工具类简化了并发编程的复杂度。原子类`Atomic`尤其重要,它提供了线程安全的变量更新方法,支持整型、长整型、布尔型、数组及对象属性的原子修改。结合`volatile`关键字,可以实现多线程环境下共享变量的安全修改。