【C#】OOP之多态那点事

看上面的UML图,我们创建一个抽象的Instrument类,类中有一个抽象方法paly,然后所有的子类都继承这个类并实现paly方法。(若不懂继承,请参照另一篇:OOP之继承那点事

我们来看一下类的实现:

    public abstract class Instrument
    {
        public abstract void Play();
    }

    public class Guitor : Instrument
    {
        public override void Play()
        {
            Console.WriteLine(string.Format("Play {0}", this.GetType().Name));
        }
    }

    public class Paino : Instrument
    {
        public override void Play()
        {
            Console.WriteLine(string.Format("Play {0}", this.GetType().Name));
        }
    }

    public class Violin : Instrument
    {
        public override void Play()
        {
            Console.WriteLine(string.Format("Play {0}", this.GetType().Name));
        }
    }
View Code

相关文章:

  • 2022-01-08
  • 2022-03-06
  • 2022-12-23
  • 2021-12-15
  • 2021-12-07
  • 2021-09-02
  • 2021-12-05
  • 2021-11-18
猜你喜欢
  • 2021-12-02
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
  • 2021-06-26
  • 2022-03-05
  • 2021-11-05
相关资源
相似解决方案