码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象多态案例

时间:2017-07-13 14:27:12      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:多态   open   read   案例   电脑开机   log   一个   public   splay   

案例:有一台有品牌的电脑他有2个功能开机和关机,它可以插2个USB接口(实现 读,写)。 一个是U盘,一个是硬盘

类图:

技术分享

 

技术分享
class Computer
    {
        private string brand;
        public IUsb IUsb_1;
        public IUsb IUsb_2;

        public string Brand
        {
            get { return brand; }
            set { brand = value; }
        }

        public Computer(string brand)
        {
            this.brand = brand;
        }

        public void Start()
        {
            Console.WriteLine("{0}品牌的电脑开机中。。。。",Brand);
        }

        public void End()
        {
            Console.WriteLine("{0}品牌的电脑关机中。。。。", Brand);
        }

    }
Computer
技术分享
 interface IUsb
    {
        void Read();
        void Write(string content);
    }
IUsb
技术分享
 class UBase:Computer,IUsb
    {
        private string content;
        public string Content
        {
            get { return content; }
            set { content = value; }
        }

       public UBase(string brand) : base(brand)
        {

        }

        public void Read()
        {
            Console.WriteLine("{0}读取数据{1}",Brand,content);
        }

        public void Write(string content)
        {
            this.content += content ;
            Console.WriteLine("{0}写入数据{1}",Brand,content);
        }

      
    }
UBase
技术分享
class UzileiA:UBase
    {
        private int content;//存储空间
        public UzileiA(string content) : base(content)
        {

        }
    }
U盘子类
技术分享
class HardB:UBase
    {
        private int content;//存储空间
        public HardB(string content) : base(content)
        {

        }
    }
Hard子类
技术分享
  class Program
    {
        static void Main(string[] args)
        {
            UBase uBase1 = new UzileiA("金士顿32G"); //里氏替换   子类可以赋值给父类
            //有一台电脑他有2个接口可以插USB 和 硬盘 
            Computer cp = new Computer("华硕");
            cp.Start();
            cp.IUsb_1 = uBase1;
            cp.IUsb_1.Write("你好。");
            cp.IUsb_1.Read();



            cp.End();
            Console.ReadKey();
        }
    }
调用

 

 

面向对象多态案例

标签:多态   open   read   案例   电脑开机   log   一个   public   splay   

原文地址:http://www.cnblogs.com/LS520/p/7159926.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!