• Java-继承,多态练习09-22-01


    1.实现如下类之间的继承关系,并编写Music类来测试这些类。

     

    父类:

    package com.lianxi;
    
    public class Instrument {
        //属性
        private String yueqi;
    
        public String getYueqi() {
            return yueqi;
        }
    
        public void setYueqi(String yueqi) {
            this.yueqi = yueqi;
        }
        //构造方法
        public Instrument(String yueqi)
        {
            this.yueqi=yueqi;
        }
    
        public Instrument() {
            super();
        }
    
        //成员方法
        public void play()
        {
            System.out.println("弹奏乐器名称:"+yueqi);
        }
    }

    package com.lianxi;
    
    
    public class Brass extends Instrument {
    
        //方法重写
            public void play()
            {
                System.out.println("弹奏Brass");
            }
            
            public void play2()
            {
                System.out.println("调用Barss的play2");
            }
        
    
    }
    package com.lianxi;
    
    public class Wind extends Instrument {
        
        //方法重写
        public void play()
        {
            System.out.println("弹奏Wind");
        }
        
        public void play2()
        {
            System.out.println("调用Wind的play2");
        }
    }

    测试:

    package com.lianxi;
    
    public class Music {
    
        public static void main(String[] args) {
            Instrument ins=new Instrument();
            tune(ins);
            Wind w=new Wind();
            Brass b=new Brass();
            w.play();
            w.play2();
            b.play();
            b.play2();
            
            
            
            
        }
        public static void tune(Instrument i)
        {
            i.setYueqi("吉他");
            i.play();
            System.out.println(i.getYueqi());
        }

    结果:

  • 相关阅读:
    从O(n^3) 到 O(n)求最大连续和
    冲刺博客NO.6
    冲刺博客NO.5
    冲刺博客NO.4
    冲刺博客NO.3
    冲刺博客NO.2
    冲刺博客NO.1
    结对开发:四则运算(网页版)
    课堂作业3
    软件工程概论02~ 四则运算
  • 原文地址:https://www.cnblogs.com/tfl-511/p/5898631.html
Copyright © 2020-2023  润新知