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
目录
打赏
0
0
0
0
19
分享
相关文章
k8s的出现解决了java并发编程胡问题了
Kubernetes通过提供自动化管理、资源管理、服务发现和负载均衡、持续交付等功能,有效地解决了Java并发编程中的许多复杂问题。它不仅简化了线程管理和资源共享,还提供了强大的负载均衡和故障恢复机制,确保应用程序在高并发环境下的高效运行和稳定性。通过合理配置和使用Kubernetes,开发者可以显著提高Java应用程序的性能和可靠性。
72 31
注解的艺术:Java编程的高级定制
注解是Java编程中的高级特性,通过内置注解、自定义注解及注解处理器,可以实现代码的高度定制和扩展。通过理解和掌握注解的使用方法,开发者可以提高代码的可读性、可维护性和开发效率。在实际应用中,注解广泛用于框架开发、代码生成和配置管理等方面,展示了其强大的功能和灵活性。
70 25
Java编程中的异常处理:从基础到高级
在Java的世界中,异常处理是代码健壮性的守护神。本文将带你从异常的基本概念出发,逐步深入到高级用法,探索如何优雅地处理程序中的错误和异常情况。通过实际案例,我们将一起学习如何编写更可靠、更易于维护的Java代码。准备好了吗?让我们一起踏上这段旅程,解锁Java异常处理的秘密!
在线编程实现!如何在Java后端通过DockerClient操作Docker生成python环境
以上内容是一个简单的实现在Java后端中通过DockerClient操作Docker生成python环境并执行代码,最后销毁的案例全过程,也是实现一个简单的在线编程后端API的完整流程,你可以在此基础上添加额外的辅助功能,比如上传文件、编辑文件、查阅文件、自定义安装等功能。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
在线编程实现!如何在Java后端通过DockerClient操作Docker生成python环境
课时6:Java编程起步
课时6:Java编程起步,主讲人李兴华。课程摘要:介绍Java编程的第一个程序“Hello World”,讲解如何使用记事本或EditPlus编写、保存和编译Java源代码(*.java文件),并解释类定义、主方法(public static void main)及屏幕打印(System.out.println)。强调类名与文件名一致的重要性,以及Java程序的编译和执行过程。通过实例演示,帮助初学者掌握Java编程的基本步骤和常见问题。
Java 并发编程——volatile 关键字解析
本文介绍了Java线程中的`volatile`关键字及其与`synchronized`锁的区别。`volatile`保证了变量的可见性和一定的有序性,但不能保证原子性。它通过内存屏障实现,避免指令重排序,确保线程间数据一致。相比`synchronized`,`volatile`性能更优,适用于简单状态标记和某些特定场景,如单例模式中的双重检查锁定。文中还解释了Java内存模型的基本概念,包括主内存、工作内存及并发编程中的原子性、可见性和有序性。
138 5
Java 并发编程——volatile 关键字解析
java并发编程中Monitor里的waitSet和EntryList都是做什么的
在Java并发编程中,Monitor内部包含两个重要队列:等待集(Wait Set)和入口列表(Entry List)。Wait Set用于线程的条件等待和协作,线程调用`wait()`后进入此集合,通过`notify()`或`notifyAll()`唤醒。Entry List则管理锁的竞争,未能获取锁的线程在此排队,等待锁释放后重新竞争。理解两者区别有助于设计高效的多线程程序。 - **Wait Set**:线程调用`wait()`后进入,等待条件满足被唤醒,需重新竞争锁。 - **Entry List**:多个线程竞争锁时,未获锁的线程在此排队,等待锁释放后获取锁继续执行。
131 12
|
4月前
|
Java多线程编程秘籍:各种方案一网打尽,不要错过!
Java 中实现多线程的方式主要有四种:继承 Thread 类、实现 Runnable 接口、实现 Callable 接口和使用线程池。每种方式各有优缺点,适用于不同的场景。继承 Thread 类最简单,实现 Runnable 接口更灵活,Callable 接口支持返回结果,线程池则便于管理和复用线程。实际应用中可根据需求选择合适的方式。此外,还介绍了多线程相关的常见面试问题及答案,涵盖线程概念、线程安全、线程池等知识点。
366 2
Java多线程编程的陷阱与解决方案####
本文深入探讨了Java多线程编程中常见的问题及其解决策略。通过分析竞态条件、死锁、活锁等典型场景,并结合代码示例和实用技巧,帮助开发者有效避免这些陷阱,提升并发程序的稳定性和性能。 ####
Java多线程编程的陷阱与最佳实践####
本文深入探讨了Java多线程编程中常见的陷阱,如竞态条件、死锁和内存一致性错误,并提供了实用的避免策略。通过分析典型错误案例,本文旨在帮助开发者更好地理解和掌握多线程环境下的编程技巧,从而提升并发程序的稳定性和性能。 ####
下一篇
oss创建bucket
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等