重写方法,重载方法,虚方法和抽象方法。

        重写方法,重载方法,虚方法和抽象方法。

        重写是指子类重新实现父类的某些方法,以实现一些新的功能。重写的关键字是override。并且重写的方法其签名是相同的。

        重载是指允许类中具有相同函数名的方法,但是其函数签名必须是唯一的(顺序,个数等)。重载的方法是在被调用的时候通过函数签名确定需要调用哪一个方法。

        虚方法,若一个实例方法的声明中含有virtual修饰符,则称该方法为虚方法(virtual method)。在调用一个虚方法时,该调用所涉及的那个实例的运行时类型

        (runtime type)确定了要被调用的究竟是该方法的哪一个实现。

        抽象方法,抽象方法是没有实现的虚方法。抽象方法只能存在于抽象类中。抽象方法使用abstract修饰符进行声明。

        抽象方法只提供函数的声明,至于函数的实现,必须要在子类中通过重写实现。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Override_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //抽象类不能实例化
            fatherClass father = new childClass();

            childClass child = new childClass();

            Console.WriteLine("fatherClass的Add方法:" + father.Add(1, 2)); //执行ChildClass中的Add方法

            Console.WriteLine("childClass重写fatherClass中的虚方法Add:" + child.Add(1, 2));  //执行ChildClass中的Add方法

            Console.WriteLine("childClass重载Add方法:"+child.Add(1)); 

            Console.WriteLine("childClass重载Add方法:" + child.Add(1,3,5));

            Console.WriteLine("childClass重写fartherClass中的抽象方法Add:" + father.StringFun("抽象方法")); //执行ChildClass中的StringFun方法 

        }
    }


    abstract class fatherClass
    {
        //构造
        public fatherClass()
        {
                
        }

        //虚方法
        public virtual int Add(int i, int j)
        {
            return i + j;
        }

        //抽象方法
        public abstract string StringFun(string str);
    }

    class childClass : fatherClass
    {
        //构造
        public childClass()
        {
                
        }

        //重写父类虚方法Add  被重写的父类方法 必须是virtual , abstract方法
        public override int Add(int i, int j)
        {
            return i*2 + j;
        }

        public int Add(int i )
        {
            return i;
        }

        public int Add(int i, int j, int k)
        {
            return i+j+k;
        }


        //重写父类的抽象方法
        public override string StringFun(string str)
        {
            return str;
        }
    }
}

 

 

 

转载于:https://www.cnblogs.com/ShuiMu/archive/2011/07/24/2115570.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值