#344 – Hidden Base Class Member Is Invoked Based on Declared Type of Object

When you use the new modifier to hide a base class method, it will still be called by objects whose type is the base class.  Objects whose type is the derived class will call the new method in the derived class.

            Dog kirby = new Dog("Kirby", 15);

            // Calls Dog.Bark
            kirby.Bark();

            Terrier jack = new Terrier("Jack", 17);

            // Calls Terrier.Bark
            jack.Bark();

The Terrier.Bark method is invoked because the variable jack is declared to be of type Terrier.

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 call the Bark method using this base class variable, the Bark method in the base class is called, even though we’re invoking the method on an instance of the derived class.

            Dog kirby = new Dog("Kirby", 15);

            // Calls Dog.Bark
            kirby.Bark();

            Dog jack = new Terrier("Jack", 17);

            // Calls Dog.Bark
            jack.Bark();
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: