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