In object-oriented languages, many different implementations of interfaces are polymorphic. Polymorphism responds to different objects in response to the same method, polymorphism in code, that is, a variety of forms, must have inheritance, no inheritance there is no polymorphism in the use of polymorphism, will be dynamic detection, to invoke the real object method
//
// main.m
// mobile
#import <Foundation / Foundation.h>
#import "Communication.h"
#import "Electrograph.h"
#import "Telephone.h"
#import "Student.h"
int main (int argc, const char * argv []) {
@autoreleasepool {
Peerson * p = [[Student alloc] init];
Communication * cuo = [[Electrograph alloc] init];
[p sayhi: cuo];
cuo = [[Communication alloc] init];
[p sayhi: cuo];
cuo = [[Telephone alloc] init];
[p sayhi: cuo];
}
return 0;
}
//
// Peerson.h
// mobile
#import <Foundation / Foundation.h>
#import "Communication.h"
@interface Peerson: NSObject
-(void) sayhi: (Communication *) say;
@end
//
// Peerson.m
// mobile
#import "Peerson.h"
@implementation Peerson
-(void) sayhi: (Communication *) say {
[say call];
}
@end
//
// Student.h
// mobile
#import "Peerson.h"
@interface Student: Peerson
@end
//
// Student.h
// mobile
#import "Peerson.h"
@interface Student: Peerson
@end
//
// Communication.h
// mobile
#import <Foundation / Foundation.h>
@interface Communication: NSObject
-(void) call;
@end
//
// Communication.m
// mobile
#import "Communication.h"
@implementation Communication
-(void) call {
NSLog (@ "I'm calling now");
}
@end
//
// Electrograph.h
// mobile
#import "Communication.h"
@interface Electrograph: Communication
@end
//
// Electrograph.m
// mobile
#import "Electrograph.h"
@implementation Electrograph
-(void) call {
NSLog (@ "I'm calling with my family");
}
@end
//
// Telephone.h
// mobile
#import "Communication.h"
@interface Telephone: Communication
@end
//
// Telephone.m
// mobile
#import "Telephone.h"
@implementation Telephone
-(void) call {
NSLog (@ "My mobile phone can access the Internet");
}
@end
Objective-c polymorphism