計算機科学のブログ

inheritance - Your object's family tree - implement subclasse, method, virtual, override

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 6(inheritance - Your object’s family tree)、p.295(Exercise)の解答を求めてみる。

コード

Pigeon.cs

namespace MyFirstConsoleApp
{
    class Pigeon : Bird
    {
        public override Egg[] LayEggs(int numberOfEggs)
        {
            Egg[] eggs = new Egg[numberOfEggs];
            for (int i = 0; i < numberOfEggs; i++)
            {
                eggs[i] = new Egg(Randomizer.NextDouble() * 2 + 1, "white");
            }
            return eggs;
        }
    }
}

コード

Ostrich.cs

namespace MyFirstConsoleApp
{
    class Ostrich : Bird
    {
        public override Egg[] LayEggs(int numberOfEggs)
        {
            Egg[] eggs = new Egg[numberOfEggs];
            for (int i = 0; i < numberOfEggs; i++)
            {
                eggs[i] = new Egg(Randomizer.NextDouble() + 12, "speckled");
            }
            return eggs;
        }
    }
}

入出力結果(Terminal, Zsh)


Press P for pigeon, O for ostrich: P
How many eggs should it lay? 4
A 2.0cm white egg
A 2.5cm white egg
A 2.5cm white egg
A 2.2cm white egg

Press P for pigeon, O for ostrich: O
How many eggs should it lay? 3
A 12.0cm speckled egg
A 12.5cm speckled egg
A 12.8cm speckled egg

Press P for pigeon, O for ostrich: