【面向对象】三重定义——重构、重写、重载


重构(Refactoring)

【定义】

在原始代码的基础上通过一定的方法,比如添加设计模式,封装类等手段,使软件的性能得到提升,从而提高软件的维护性和拓展性。

【关键代码】

  //父类
    class Animal
    {
        ......
        public string Shout()
        {
            string result=""
            for(int i=0;i<ShoutNum;i++)
                result +=getShoutSound()+",";

            return "我的名字叫"+name+""+result ;

        }

        protected virtual string getShoutSound()
        {
            return "";
        }
    }

    //子类
    class Cat:Animal 
    {
        public Cat():base()
        {}
        public Cat(string name):base(name)
        {}
        protected override string getShoutSound()
       {
 	       return "喵";
        }
    }

重写(Overriding)

【定义】

子类继承父类的方法时,想做一些修改,这就用到了方法的重写,又称方法覆盖。

【关键代码】

//抽象类animal-----------------------------
   class Animal
     {
        protected string name = "";
        public Animal(string name)
        {
            this.name = name;
        }
        protected int shouNum = 3;
        public int ShoutNum
        {
            get { return shouNum;}
            set { shouNum = value; }
        
        }
      public string shout()
        {
               string result="";
                for (int i = 0; i <shouNum; i++)
                result += "";
                return "我的名字叫" + name + "" + result;  
        }
    //虚拟方法:主要重写的方法
        protected virtual string getshoutsound()   
        {
            return "";
        }
    }
    //类cat
        class Cat : Animal
        {
            public Cat(string name)
                : base(name)
            { }
         //类cat对方法getshoutsound()进行了重写覆盖
            public override string getshoutsound()    
            {
                return "喵";
            }
        }

重载(Overloading)

【定义】

遇到函数或方法有相同的名称,但参数列表不同的情况,可用方法重载

【关键代码】

class Cat
    {
        private string name="";
        public Cat(string name)
        {
            this.name=name;
        }

        public Cat()
        {
            this.name="无名";
        }

        public string Shout()
        {
            return "我的名字叫"+name+"喵";
        }
    }

小结

“一张图胜过千言万语”,在以后的总结中要多加些图帮助理解。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡夫卡的熊kfk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值