inheritance - Your object's family tree - virtual and override
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.301(mini sharpen your pencil)の解答を求めてみる。
コード
Program.cs
SafeOwner owner = new SafeOwner();
Safe safe = new Safe();
JewelThief jewelThief = new JewelThief();
// Thank you for returning my precious jewels!
jewelThief.OpenSafe(safe, owner);
// Console.ReadKey(true);
class Safe
{
private string contents = "precious jewels";
private string safeCombination = "12345";
public string Open(string combination)
{
if (combination == safeCombination)
{
return contents;
}
return "";
}
public void PickLock(LockSmith lockpicker)
{
lockpicker.Combination = safeCombination;
}
}
class SafeOwner
{
private string valuables = "";
public void ReceiveContents(string safeContents)
{
valuables = safeContents;
Console.WriteLine($"Thank you for returning my {valuables}!");
}
}
class LockSmith
{
public void OpenSafe(Safe safe, SafeOwner owner)
{
safe.PickLock(this);
string safeContents = safe.Open(Combination);
ReturnContents(safeContents, owner);
}
public string Combination { private get; set; }
protected void ReturnContents(string safeContents, SafeOwner owner)
{
owner.ReceiveContents(safeContents);
}
}
class JewelThief : LockSmith
{
private string stolenJewels;
protected void ReturnContents(string safeContents, SafeOwner owner)
{
stolenJewels = safeContents;
Console.WriteLine($"I'm stealing the jewels! I stole: {stolenJewels}");
}
}
入出力結果(Terminal, Zsh)
% dotnet run
/…/ConsoleApp5/Program.cs(52,20): warning CS0108: 'JewelThief.ReturnContents(string, SafeOwner)' hides inherited member 'LockSmith.ReturnContents(string, SafeOwner)'. Use the new keyword if hiding was intended. [/…/ConsoleApp5/ConsoleApp5.csproj]
/…/ConsoleApp5/Program.cs(43,19): warning CS8618: Non-nullable property 'Combination' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. [/…/ConsoleApp5/ConsoleApp5.csproj]
/…/ConsoleApp5/Program.cs(51,20): warning CS8618: Non-nullable field 'stolenJewels' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. [/…/ConsoleApp5/ConsoleApp5.csproj]
Thank you for returning my precious jewels!
%