#356 – Hidden Base Class Property Is Used Based on Declared Type of Object
June 29, 2011 1 Comment
When you use the new modifier to hide a base class property, its property accessors will still be called by objects whose type is the base class. Objects whose type is the derived class will use the new property in the derived class.
Dog kirby = new Dog("Kirby", 15); kirby.Temperament = "EAGER"; Console.WriteLine(kirby.Temperament); // Kirby is eager Terrier jack = new Terrier("Jack", 15); jack.Temperament = "CraZY"; Console.WriteLine(jack.Temperament); // Terrier Jack is CRAZY
We could also use a variable of type Dog (the base class) to refer to an instance of a Terrier (the derived class). If we then reference the Temperament property using this base class variable, the Temperament property in the base class is used, even though we’re working with an instance of the derived class.
Dog kirby = new Dog("Kirby", 15); kirby.Temperament = "EAGER"; // Uses Dog.Temperament Dog jack = new Terrier("Jack", 15); jack.Temperament = "CraZY"; // Also uses Dog.Temperament
Okay, This is intriguing. If I remember right, if
Dog jack = new Terrier(“Jack”, 15);
calls up Dog’s properties and methods for jack, – instead of Terrier’s, what meaningful membership does Jack have in the Terrier class? static variables? I don’t see what Jack inherits from Terrier. (apart from Terrier genes!)