【转载】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

【转载】Accessing a Derived Class Using a Base Class Variable,布布扣,bubuko.com

【转载】Accessing a Derived Class Using a Base Class Variable

上一篇:MAYA动力学中的场知识介绍


下一篇:Photoshop解析笔刷流量和不透明度的区别