Solarion
Honorary Master
- Joined
- Nov 14, 2012
- Messages
- 28,051
- Reaction score
- 17,804
I'm looking at the following, specifically the JewelThief.ReturnContents (safe, owner) method. I was expecting the jewelThief's ReturnContents method to shadow the LockSmith's ReturnContents method because it has the same name, however it is not. I specifically have to override and virtual on JewelThief and Locksmith methods respectively.
For example, I created a PrintDate() test method in both LockSmith and JewelThief and yes, that method shadowed the LockSmith's PrintDate method. Here I did not have to specify override and virtual.
What is the difference? Why does it work for one and not the other aka why does a child method hide a base class method sometimes but then at other times it does not?
For example, I created a PrintDate() test method in both LockSmith and JewelThief and yes, that method shadowed the LockSmith's PrintDate method. Here I did not have to specify override and virtual.
What is the difference? Why does it work for one and not the other aka why does a child method hide a base class method sometimes but then at other times it does not?
PHP:
class Jewels
{
public string Sparkle()
{
return "Sparkle, sparkle!";
}
}
PHP:
class Safe
{
private Jewels contents = new Jewels();
private string safeCombination = "12345";
public Jewels Open(string combination)
{
if (combination == safeCombination)
return contents;
else
return null;
}
public void PickLock(Locksmith lockpicker)
{
lockpicker.WriteDownCombination(safeCombination);
}
}
PHP:
class Owner
{
private Jewels returnedContents;
public void ReceiveContents(Jewels safeContents)
{
returnedContents = safeContents;
Console.WriteLine("Thank you for returning my jewels! " + safeContents.Sparkle());
}
}
PHP:
class Locksmith
{
public void OpenSafe(Safe safe, Owner owner)
{
safe.PickLock(this);
Jewels safeContents = safe.Open(writtenDownCombination);
ReturnContents(safeContents, owner);
}
private string writtenDownCombination = null;
public void WriteDownCombination(string combination)
{
writtenDownCombination = combination;
}
public void ReturnContents(Jewels safeContents, Owner owner)
{
owner.ReceiveContents(safeContents);
}
}
PHP:
class JewelThief : Locksmith
{
private Jewels stolenJewels = null;
public void ReturnContents(Jewels safeContents, Owner owner)
{
stolenJewels = safeContents;
Console.WriteLine("I'm stealing the contents! " + stolenJewels.Sparkle());
}
}
PHP:
class Program
{
static void Main(string[] args)
{
Owner owner = new Owner();
Safe safe = new Safe();
JewelThief jewelThief = new JewelThief();
jewelThief.OpenSafe(safe, owner);
Console.ReadKey();
}
}