zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }

    结果:

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

  • 相关阅读:
    leetcode69
    leetcode204
    leetcode414
    leetcode532
    leetcode28
    leetcode155
    leetcode303
    leetcode190
    2018-7-21-win10-uwp-调用-Microsoft.Windows.Photos_8wekyb3d8bbwe-应用
    2018-7-21-win10-uwp-调用-Microsoft.Windows.Photos_8wekyb3d8bbwe-应用
  • 原文地址:https://www.cnblogs.com/Lhuatao/p/3533832.html
Copyright © 2011-2022 走看看