C#学习笔记:类继承中的virual和override关键字的使用

参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P77

类继承中的virual和override关键字的使用

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

namespace Example3_8
{
    //基类
    public class Person
    {
        public virtual void Work()
        {
            Console.WriteLine("调用了基类Person类的Work方法");
        }
    }
    //派生类
    public class Student : Person 
    {
        public override void Work()
        {
            Console.WriteLine("调用了派生类Student类的Work方法");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu.Work();

            Person ps = new Person();
            ps.Work();
            Console.ReadKey();
        }
    }
}

运行结果如下:

从结果可以看出,定义派生类对象stu,调用stu.work()时,运行的是派生类定义的方法。

发布了42 篇原创文章 · 获赞 1 · 访问量 988

猜你喜欢

转载自blog.csdn.net/qq_41708281/article/details/104232949