計算機科学のブログ

inheritance - Your object's family tree - extending a base class

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

コード

Program.cs

while (true)
{
    Bird bird;
    Console.Write("\nPress P for pigeon, O for ostrich: ");
    Char key = Char.ToUpper(Console.ReadKey().KeyChar);
    if (key == 'P')
    {
        bird = new Pigeon();
    }
    else if (key == 'O')
    {
        bird = new Ostrich();
    }
    else
    {
        break;
    }
    Console.Write("\nHow many eggs should it lay? ");
    if (!int.TryParse(Console.ReadLine(), out int numberOfEggs))
    {
        break;
    }
    Egg[] eggs = bird.LayEggs(numberOfEggs);
    foreach (Egg egg in eggs)
    {
        Console.WriteLine(egg.Description);
    }
}

class Egg
{
    public double Size { get; private set; }
    public string Color { get; private set; }
    public Egg(double size, string color)
    {
        Size = size;
        Color = color;
    }
    public string Description { get { return $"A {Size:0.0}cm {Color} egg"; } }
}
class Bird
{
    public static Random Randomizer = new Random();
    public virtual Egg[] LayEggs(int numberOfEggs)
    {
        Console.Error.WriteLine("Bird.LayEggs should never get called");
        return new Egg[0];
    }
}
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(1 + Randomizer.NextDouble() * 2, "white");
        }
        return eggs;
    }
}
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(12 + Randomizer.NextDouble(), "speckled");
        }
        return eggs;
    }
}

入出力結果(Terminal, Zsh)

% dotnet run

Press P for pigeon, O for ostrich: p
How many eggs should it lay? 4
A 1.8cm white egg
A 2.6cm white egg
A 1.7cm white egg
A 1.3cm white egg

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

Press P for pigeon, O for ostrich: q%