#356 – Hidden Base Class Property Is Used Based on Declared Type of Object

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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #356 – Hidden Base Class Property Is Used Based on Declared Type of Object

  1. stravinsky7 says:

    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!)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: