inheritance - Your object's family tree - base class, sub class, 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.293(Exercise)の解答を求めてみる。
コード
Program.cs
using System;
namespace MyFirstConsoleApp
{
class A
{
public int ivar = 7;
public virtual string m1()
{
return "A's m1, ";
}
public string m2()
{
return "A's m2, ";
}
public virtual string m3()
{
return "A's m3, ";
}
}
class B: A
{
public override string m1()
{
return "B's m1, ";
}
}
class C:B
{
public override string m3()
{
return "C's m3, " + (ivar + 6);
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
A a2 = new C();
string q = b.m1() + c.m2() + a.m3();
Console.WriteLine(q == "B's m1, A's m2, A's m3, ");
q = c.m1() + c.m2() + c.m3();
Console.WriteLine(q == "B's m1, A's m2, C's m3, 13");
q = a.m1() + b.m2() + c.m3();
Console.WriteLine(q == "A's m1, A's m2, C's m3, 13");
q = a2.m1() + a2.m2() + a2.m3();
Console.WriteLine(q == "B's m1, A's m2, C's m3, 13");
}
}
}
入出力結果(Terminal, Zsh)
True
True
True
True