Translate

> > Polymorphism

Polymorphism

Posted on Monday, October 24, 2011 | No Comments

Polymorphism is the ability of an object of one class to appear and be used as an object 
of another class. This is usually done by creating methods and attributes that are similar to 
those of another class. 
// file: Animal.h
#import <Foundation/Foundation.h>
 
@interface Animal : NSObject
{
        NSString *name;
}
 
@property(copy) NSString *name;
 
-(id) initWithName: (NSString *) aName;
 
-(void) talk;
 
@end
 
// =============================
 
// file: Animal.m
#import "Animal.h"
 
@implementation Animal
 
@synthesize name;
 
-(id) initWithName:(NSString *)aName {
        self = [super init];
 
        if ( self ) 
                self.name = aName;
 
        return self;
}
 
-(id) init {
        return [self initWithName:@""];
}
 
-(void) talk {
        NSLog(@"%@: Animals cannot talk!", name);
}
 
-(void) dealloc {
        if ( name )
                [name release];
        [super dealloc];
}
 
@end
 
// =============================
 
// file: Cat.h
#import "Animal.h"
 
@interface Cat : Animal
 
-(void) talk;
 
@end
 
// =============================
 
// file: Cat.m
#import "Cat.h"
 
@implementation Cat
 
-(void) talk {
        NSLog(@"%@: Meow!", name);
}
 
@end
 
// =============================
 
// file: Dog.h
#import "Animal.h"
 
@interface Dog : Animal
 
-(void) talk;
 
@end
 
// =============================
 
// file: Dog.m
#import "Dog.h"
 
@implementation Dog
 
-(void) talk {
        NSLog(@"%@: Woof! Woof!", name);
}
 
@end
 
// =============================
 
// file: main.m
#import <Foundation/Foundation.h>
#import "Animal.h"
#import "Cat.h"
#import "Dog.h"
 
int main (int argc, const char * argv[])
{
        // all instances are behind a superclass type (Animal)
        Animal *animal = [[Animal alloc] initWithName:@"Animal"];
        Animal *missy = [[Cat alloc] initWithName:@"Missy"];
        Animal *mr = [[Cat alloc] initWithName:@"Mr. Mistophelees"];
        Animal *lassie = [[Dog alloc] initWithName:@"Lassie"];
 
        // polymorphic behavior
        [animal talk];
        [missy talk];
        [mr talk];
        [lassie talk];
 
        // releasing memory
        [animal release];
        [missy release];
        [mr release];
        [lassie release];
 
    return 0;
}
 
// =============================
 
// --> Console output:
// Animal: Animals cannot talk!
// Missy: Meow!
// Mr. Mistophelees: Meow!
// Lassie: Woof! Woof!

Leave a Reply

Powered by Blogger.