【转载】#335 - Accessing a Derived Class Using a Base Class Variable

You can use a variable whose type is a base class to reference instances of a derived class.

However, using the variable whose type is the base class, you can use it to access only members of the base class and not members of the derived class.

In the example below, we have two instances of the Terrier class, which derives from Dog. One instance is referenced by a variable of type Terrier. Using this variable, you have access to all members of the Terrier class. On the other hand, the variable whose type is Dog can only reference members of the Dog class, even though the reference points to an instance of a Terrier.

1 Terrier bubba = new Terrier("Bubba", 2, "Happy");
2 bubba.Growl();         // Can call Terrier.Growl
3 
4 Dog jack = new Terrier("Jack", 17, "Surly");
5 jack.Growl();             // ERROR: Can't call Growl method

 原文地址:#335 - Accessing a Derived Class Using a Base Class Variable

posted on 2014-03-11 19:28  yuthreestone  阅读(226)  评论(0编辑  收藏  举报

导航