zoukankan      html  css  js  c++  java
  • 抽象,密封,多态和继承的例子

    一,父类Animal

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Test3
    {
        public abstract class Animal
        {
            //获得声音的方法
            public virtual string GetShoutSound()
            {
                return "";
            }
        }
    }

    二,子类Cat和Dog

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Test3
    {
        public class Dog : Animal
        {
            public override string GetShoutSound()
            {
                return "旺旺旺旺!!!!!";
            }
        }
    }

    子类二

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Test3
    {
        public class Cat : Animal
        {
            //重写抽象方法中的,虚方法
            public override string GetShoutSound()
            {
                return "喵喵喵喵!!!!!";
            }
        }
    }

    三,密封功能类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Test3
    {
        //密封Dog的speak功能,密封类不可以被继承
        sealed class Speak : Dog
        {
            public string DogSpeak()
            {
                return this.GetShoutSound();
            }
        }
    }

    四,输出:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Test3
    {
        class Program
        {
            static void Main(string[] args)
            {
                Animal animal1 = new Dog();
                Animal animal2 = new Cat();
                Speak speak = new Speak();
                string a1 = animal1.GetShoutSound();
                string a2 = animal2.GetShoutSound();
                string a3 = speak.DogSpeak();    //实现密封的功能
                Console.WriteLine(a1 + a2 + "密封功能实现:" + a3);
            }
        }
    }
  • 相关阅读:
    1137. 第 N 个泰波那契数
    486. 预测赢家
    python函数—函数的参数+递归函数
    python函数—调用函数+定义函数
    Seize the day
    数学建模基础学习2-matlab + lingo
    Python基础--使用list和tuple+条件判断+使用dict和set
    经济学人精读丨中国的电子商务
    数学建模基础学习1
    C盘今天爆掉了,罪魁祸首--百度云管家
  • 原文地址:https://www.cnblogs.com/May-day/p/5835783.html
Copyright © 2011-2022 走看看