继承-练习

news/2024/7/7 18:59:04

T3、编写程序实现乐手弹奏乐器。乐手可以弹奏不同的乐器从而发出不同的声音。可以弹奏的乐器包括二胡、钢琴和琵琶。要求:

  1. 定义乐器类Instrument,包括方法makeSound()
  2. 定义乐器类的子类:二胡Erhu、钢琴Piano和小提琴Violin
  3. 定义乐手类Musician,可以弹奏各种乐器play(Instrument instrument)
  4. 定义测试类,给乐手不同的乐器让他弹奏。
public class Instrument {//父类
    public void makeSound(){
        System.out.println("乐器发出声音");
    }
}
public class Erhu extends Instrument{//子类1
    public void makeSound() {
        System.out.println("乐手弹奏二胡,发出二胡声");
    }
}
public class Piano extends Instrument{//子类2
    public void makeSound() {
        System.out.println("乐手弹奏钢琴,发出钢琴声");
    }
}
public class Violin extends Instrument{//子类3
    public void makeSound() {
        System.out.println("乐手弹奏小提琴,发出小提琴声");
    }
}
public class Musician {//乐手类
    //类Musician 有方法play(Instrument instrument)
    public void play(Instrument instrument){
        instrument.makeSound();
    }
}
public class TestMusic {//测试类
    public static void main(String[] args) {
        Musician musician = new Musician();
        Erhu erhu = new Erhu();
        Piano piano = new Piano();
        Violin violin = new Violin();

        musician.play(erhu);
        musician.play(piano);
        musician.play(violin);
    }
}


http://lihuaxi.xjx100.cn/news/2122742.html

相关文章

python函数-变量和参数-2.4

目录 在高阶函数中使用匿名函数 map() 函数: sorted() 函数: filter() 函数: 函数练习-9 在高阶函数中使用匿名函数 map() 函数: 描述: map() 会根据提供的函数对指定序列做映射。 第一个参数 function 以参数序…

P1383 高级打字机(可持续化线段树)

题目描述 早苗入手了最新的高级打字机。最新款自然有着与以往不同的功能,那就是它具备撤销功能,厉害吧。 请为这种高级打字机设计一个程序,支持如下 33 种操作: T x:Type 操作,表示在文章末尾打下一个小…

[GWCTF 2019]xxor

知识要点: Z3和tea __int64 __fastcall main(int a1, char **a2, char **a3) {int i; // [rsp8h] [rbp-68h]int j; // [rspCh] [rbp-64h]__int64 v6[6]; // [rsp10h] [rbp-60h] BYREF__int64 v7[6]; // [rsp40h] [rbp-30h] BYREFv7[5] __readfsqword(0x28u);puts…

想要成为一名合格的软件测试工程师,你得会些啥?

对于很多新入行或者打算入行,成为软件测试工程师的小伙伴来说,刚开始接触这行,不知道自己究竟该学些什么,或者不知道必须掌握哪些知识,才能成为一名合格的测试工程师。 根据笔者观点,如果你能在学习过程中&…

chatglm-6b模型在windows的详细安装教程(踩坑记录)

1.先是看了github的文章(如果打不开这篇文章,可能需要科学上网,即访问外网的VPN): https://github.com/THUDM/ChatGLM-6B 强烈建议科学上网,不然后序下载相关文件也是困难重重,浪费时间&#x…

鸿蒙 ohpm 的异常报错

解压安装 ohpm , 进入 command-line-tools/ohpm/bin 目录执行 ohpm -v , 一直提示未初始化异常:ERROR: ohpm has not been initialized yet. Execute the init script to initialize it first. google搜索发现都是让配置环境变量、执行init脚本,尝试后…

vue3 Element-Plus封装的el-tree-select的使用

更多ruoyi-nbcio功能请看演示系统 gitee源代码地址 前后端代码: https://gitee.com/nbacheng/ruoyi-nbcio 演示地址:RuoYi-Nbcio后台管理系统 http://122.227.135.243:9666/ 更多nbcio-boot功能请看演示系统 gitee源代码地址 后端代码&#xff1a…

基于Qt的插件扩展

基于Qt的插件进行扩展 定义插件接口 #if defined(WORKFLOW_LIBRARY) # define WORKFLOW_EXPORT Q_DECL_EXPORT #else # define WORKFLOW_EXPORT Q_DECL_IMPORT #endifclass WORKFLOW_EXPORT IPlugin { public:virtual ~IPlugin() {}virtual void initModelRegistry(QString…