計算機科学のブログ

interfaces, casting, and "is" - Making classes keep their promises - abstract class, implements, inheritences

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 7(interfaces, casting, and “is” - Making classes keep their promises)、p.367(Pool Puzzle)の解答を求めてみる。

コード

using System;

namespace MyFirstConsoleApp
{
    interface INose
    {
        public int Ear();
        string Face { get;}
    }
    abstract class Picasso : INose
    {
        private string fase;
        public virtual string Face => fase;
        public abstract int Ear();
        public Picasso(string fase)
        {
            this.fase = fase;
        }
    }
    class Clowns : Picasso
    {
        public Clowns() : base("Clowns") { }

        public override int Ear()
        {
            return 7;
        }
    }
    class Acts: Picasso
    {
        public Acts() : base("Acts") { }
        public override int Ear()
        {
            return 5;
        }
    }
    class Of2016 : Clowns
    {
        public override string Face => "Of2016";
        static void Main(string[] args)
        {
            string result = "";
            INose[] i = new INose[]
            {
                new Acts(),
                new Clowns(),
                new Of2016()
            };
            foreach (INose item in i)
            {
                result += $"{item.Ear()} {item.Face}\n";
            }
            Console.WriteLine(result);
        }
    }
}

入出力結果(Terminal, Zsh)

5 Acts
7 Clowns
7 Of2016