看上面的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)); } }