在面向对象语言中,接口的多种不同的实现方式即为多态。
多态对于不同对象响应同一个方法时做出不同反应
多态在代码中的体现,即为多种形态,必须要有继承,没有继承就没有多态
在使用多态时,会进行动态检测,以调用真是的对象方法
// // 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(@"我正在打电话呢"); } @end
// // Electrograph.h // mobile #import "Communication.h" @interface Electrograph : Communication @end // // Electrograph.m // mobile #import "Electrograph.h" @implementation Electrograph -(void)call{ NSLog(@"我正在和就家人打电话"); } @end
// // Telephone.h // mobile #import "Communication.h" @interface Telephone : Communication @end // // Telephone.m // mobile #import "Telephone.h" @implementation Telephone -(void)call{ NSLog(@"我的手机能上网"); } @end