Pages

Sunday, May 13, 2012

Polymorphism and Inheritance in Objective C

Back to Main Menu

Polymorphism
Polymorphism is the ability to have more than one form in brief, the methods with the same name in different classes.
see more on here to view examples


Inheritance
We can also implement inheritance in Objective-C.  Inheritance enables programmer to inherit  methods and properties from other class, this is known as inheritance. In inheritance there are two  types class Base Class and  Sub Class. Base class is the class that all sub classes inherit so all the sub class have the property of base class.

Example 

//Base Class
@interface A: NSObject
{
}
-(void) ab;
-(void)bc;
@end

@implementation A
-(void) ab
{
   NSLog(@"at Method ab from class A");
}
-(void) bc
{
   NSLog(@"at Method bc from class A");
}
@end

//Sub Class
@interface B: A
{
}
-(void) c;
-(void) d;
@end

@implementation B
-(void) c
{
   NSLog(@"at Method c from class B");
}
-(void) d
{
   NSLog(@"at Method d from class B");
}
@end

int main()
{
   @autoreleasepool {
     B *obj=[[B init] alloc];
     [obj ab];
      [obj bc];
       [obj c];
       [obj d];
      [obj release];
    }
}

No comments:

Post a Comment