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,古老的榕树,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。