#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.

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

2 

3 // Calls Dog.Bark

4 kirby.Bark();

5 

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

7 

8 // Calls Terrier.Bark

9 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.

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

2 

3 // Calls Dog.Bark

4 kirby.Bark();

5 

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

7 

8 // Calls Dog.Bark

9 jack.Bark();

 原文地址:#344 - Hidden Base Class Member Is Invoked Based on Declared Type of Object

你可能感兴趣的:(object)