private static void Chapter73() { // 7.3.1 Inheriting Fields and Properties HouseCat garfield = new HouseCat("Garfield", 12.0); garfield.Eat(); Console.WriteLine(garfield.Tired); // prints true // 7.3.2 Base HouseCat spike = new HouseCat("Spike"); Console.WriteLine(spike.Weight); // prints 0 spike.Weight = 13; Console.WriteLine(spike.Weight); // prints 13 // 7.3.3 override // We've been introduced to the override keyword already in a previous lecture when // we were overriding the ToString, Equals and GetHashCode methods that are all // present in the base Object class. // When we want to modify the behavior of a method in the base class, we can override it in sub-classes // In order to accomplish this in our Cat/HouseCat example we will require another new keyword, virtual Cat plainCat = new Cat(8.6); HouseCat cheshireCat = new HouseCat("Cheshire Cat", 26.0); Console.WriteLine(plainCat.Noise()); // prints "Meow!" Console.WriteLine(cheshireCat.Noise()); // prints "Hello, my name is Cheshire Cat!" }
private static void Chapter75() { // 7.5 Casting // We've seen casting before when writing our Equals methods in a previous lecture. // Casting allows us to exploit one of the pillars of OOP, more specifically polymorphism. // Note: We are declaring suki as a Cat and instantiating as a HouseCat Cat suki = new HouseCat("Suki", 8); suki.Noise(); // Meow! // Results in a compiler error, since Cat doesn't have such a method // suki.IsSatisfied(); // How do we avoid this? Declare suki as a HouseCat... OR... cast suki to a HouseCat // As long as suki really is a HouseCat, this works (suki as HouseCat).IsSatisfied(); // Side note: We can check beforehand to make sure that suki really is of class HouseCat // before casting, this will prevent a runtime exception being thrown if (suki is HouseCat) { // Since this is true, we can safely cast suki to a HouseCat (suki as HouseCat).IsSatisfied(); } }