Blackhorse programmer 10-benefits and limitations of using Polymorphism

Source: Internet
Author: User

--- Java training, Android training, IOS training, and. Net training. We look forward to communicating with you! ---

Benefits of using Polymorphism

If the parameter of the function \ method is of the parent class type, both the parent class and the subclass object can be passed in.

1 # import <Foundation/Foundation. h> 2 // animal Class 3 @ interface animal: nsobject 4-(void) Eat; 5 @ end 6 @ implementation animal 7-(void) eat 8 {9 nslog (@ "Animal --- eat"); 10} 11 @ end12 13 // Dog class 14 @ interface dog: animal15-(void) run; 16 @ end17 @ implementation dog18-(void) run19 {20 nslog (@ "Dog --- Run"); 21} 22-(void) eat23 {24 nslog (@ "Dog --- eat"); 25} 26 @ end27 28 // cat class 29 @ interface Cat: animal30-(void) Eat; 31 @ end32 @ implementation cat33-(void) eat34 {35 nslog (@ "cat --- eat "); 36} 37 @ end38 39 // define a function to feed animals 40 void feed (animal * A) 41 {42 [A eat]; 43} 44 int main (INT argc, const char * argv []) 45 {46 // The function parameter is of the parent class type. Both the parent class and the subclass object can be passed in 47 animal * AA = [animal new]; 48 feed (AA); 49 50 51 dog * D = [dog new]; 52 feed (d); 53 cat * c = [Cat new]; 54 feed (C ); 55 56 // The parent class object cannot directly call the subclass method. The subclass method 57 animal * animal1 = [dog new] must be strongly converted to the subclass type. 58 // The parent class object cannot directly call the subclass method 59 // [animal1 run] 60 dog * a1 = (dog *) animal1; 61 [a1 run]; 62 Return 0; 63}

 

 

Limitations:

1> a variable of the parent class type cannot directly call the method unique to the subclass.

2> the unique method of the subclass can be called only after the subclass type variable is strongly converted.

 

Blackhorse programmer 10-benefits and limitations of using Polymorphism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.