C#で継承とかポリモーフィズムとか(2) 抽象クラスとかインターフェースとか
抽象クラスを使ってみた。
abstract class AbstractSuper { public void Process() { Prepare(); Execute(); } abstract protected void Prepare(); abstract protected void Execute(); } class ImplA : AbstractSuper { protected override void Prepare () { Console.WriteLine ("Prepare ImplA"); } protected override void Execute () { Console.WriteLine ("Execute ImplA"); } } class ImplB : AbstractSuper { protected override void Prepare () { Console.WriteLine ("Prepare ImplB"); } protected override void Execute () { Console.WriteLine ("Execute ImplB"); } } class MainClass { public static void Main (string[] args) { new ImplA().Process(); Console.WriteLine (); new ImplB().Process(); } }
特に違うところは無いのかな?
Prepare ImplA Execute ImplA Prepare ImplB Execute ImplB
インターフェースを使ってみた。
interface IHogeHoge { void Hello(); void HogeHoge(); } interface IFugaFuga { void Hello(); void FugaFuga(); } class Impl : IHogeHoge, IFugaFuga { public void Hello () { Console.WriteLine ("Hello"); } public void FugaFuga () { Console.WriteLine ("FugaFuga"); } public void HogeHoge () { Console.WriteLine ("HogeHoge"); } } class MainClass { public static void Main (string[] args) { Impl impl = new Impl(); impl.FugaFuga(); impl.HogeHoge(); impl.Hello(); } }
override書かないんだ。
実行結果は,
FugaFuga HogeHoge Hello
次みたいなこともできる。
interface IHogeHoge { void Hello(); void HogeHoge(); } interface IFugaFuga { void Hello(); void FugaFuga(); } class Impl : IHogeHoge, IFugaFuga { void IHogeHoge.Hello () { Console.WriteLine ("HogeHoge Hello"); } void IFugaFuga.Hello () { Console.WriteLine ("FugaFuga Hello"); } public void FugaFuga () { Console.WriteLine ("FugaFuga"); } public void HogeHoge () { Console.WriteLine ("HogeHoge"); } } class MainClass { public static void Main (string[] args) { Impl impl = new Impl(); impl.FugaFuga(); impl.HogeHoge(); ((IHogeHoge)impl).Hello(); ((IFugaFuga)impl).Hello(); } }
なるほど。
要キャスト。