計算機科学のブログ

inheritance - Your object's family tree - base class, subclass

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.287(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

using ConsoleApp2;

// コンパイルできないのをコメントアウト
Canine canis = new Dog();
// Wolf charon = new Canine();
Wolf charon = new Wolf();
charon.IsArboreal = false;
Hippo bailey = new Hippo();
bailey.Roam();
bailey.Sleep();
bailey.Swim();
bailey.Eat();

// Dog fido = canis;
Dog fido = new Dog();
Animal visitorPe = fido;
Animal harvey = bailey;
harvey.Roam();
// harvey.Swim();
harvey.Sleep();
harvey.Eat();

// Hippo brutus = harvey;
Hippo brutus = new Hippo();
brutus.Roam();
brutus.Sleep();
brutus.Swim();
brutus.Eat();

Canine london = new Wolf();
// Wolf egypt= london;
Wolf egypt = new Wolf();
egypt.HuntWithPack();
egypt.HuntWithPack();
egypt.AlphaInPack = false;
// Dog rex = london;
Dog rex = new Dog();
rex.Fetch();

Animals.cs

using System;

namespace ConsoleApp2;

class Animal
{
    public void Roam() { Console.WriteLine("Roam"); }
    public void Sleep() { Console.WriteLine("Sleep"); }
    public void Eat() { Console.WriteLine("Eat"); }
}
class Hippo : Animal
{
    public void Swim() { Console.WriteLine("Swim"); }
}
class Canine : Animal
{
    public bool AlphaInPack;
    public bool IsArboreal;
}
class Wolf : Canine
{
    public void HuntWithPack() { Console.WriteLine("HuntWithPack"); }
}
class Dog : Canine
{
    public void Fetch() { Console.WriteLine("Fetch"); }
}

入出力結果(Terminal, Zsh)

% dotnet run
Roam
Sleep
Swim
Eat
Roam
Sleep
Eat
Roam
Sleep
Swim
Eat
HuntWithPack
HuntWithPack
Fetch
%