Sunday, May 22, 2016

Objective C Polymorphism

Before discussing Polymorphism, Please have a look at Dynamic Binding which enables Polymorphism.

Polymorphism comes when we have hierarchy of classes with Method overriding.


                         



Let's take a BaseClass and Subclass. In my case, this is Parent and a Child. Both of them having a similar action like 'doYourJob'. Though it's a similar kind of job, both Parent and Child have to implement them differently.



 @interface Parent : NSObject

   - (void)doYourJob;

 @end

 @interface Child : Parent

   - (void)doYourJob;


 @end





   
Parent * parentObj = [Parent alloc] init];
   [parentObj doYourJob];   //go to OFFICE


   Child * childObj = [Child alloc] init];
   [childObj doYourJob];     //go to SCHOOL


When we call 'doYourJob' method on parent object, parent object's method will get called. If we call that on child object. child object's method will get called which performs a different action.

Thus, Based on the object which is calling the method, The respective method will get called. This is called Polymorphism, having different forms. Dynamic Binding enables this.


Hope this post is useful. Feel free to comment in case of any queries.


                         



No comments:

Post a Comment