• C#面向对象(二)之抽象类实现多态


    一、什么叫做多态?

    统一操作作用于不同类的实例,不同类将进行不同的解释,最后产生不同的执行结果。

    简单来说就是统一指令,对于不同的个体会产生不同的行为。

    二、如何通过抽象方法实现多态?

    1.创建一个基类people.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace 继承之抽象类
    {
        abstract class people  //抽象类
        {
    
           public abstract void SayHi();//抽象方法
          
        }
    }

    2.创建两个子类分别为Student.cs和Teacher.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace 继承之抽象类
    {
        class Student:people  //继承抽象类Peoper
        {
            public override void SayHi()   //override重写抽象方法
            {
                Console.WriteLine("你好我是学生");
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace 继承之抽象类
    {
        class Teacher:people  //继承抽象类Peoper
        {
    
            public override void SayHi()   //重写抽象类Poeoer中的抽象方法SayHi()
            {
               Console.WriteLine("你好我是老师");
            }
        }
    }

    3.输出结果Program.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace 继承之抽象类
    {
        class Program
        {
           static List<people> peopers = new List<people>();  //定义一个泛型实例
    
            public static void InitData()
            {
                Student st = new Student();
    
                Teacher tc = new Teacher();
    
                peopers.Add(st);
                peopers.Add(tc);
    
            }
            public static void Start()
            {
                foreach (people peoper in peopers)  //遍历泛型实例
                {
                    peoper.SayHi();
                }
            }
    
            static void Main(string[] args)
            {
                InitData();
                Start();
                Console.ReadLine();
            }
        }
    }

    结果:

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  • 相关阅读:
    简单介绍 CPU 的工作原理
    Converting a MatchCollection to string array
    Ubuntu18.04安装pycharm如何显示锁定图标到收藏夹
    MFC使用控制台
    将CString输出到控制台的方法
    Python 字符串前面加u,r,b的含义
    Converting a MatchCollection to string array
    git命令查看版本记录
    git命令查看版本记录
    SQL Server游标
  • 原文地址:https://www.cnblogs.com/Lhuatao/p/3533832.html
Copyright © 2020-2023  润新知