多态简单来说就是允许将子类类型的指针赋给父类类型的指针。写代码的时候呢,把不同的子类当作父类来看,可以屏蔽子类对象之间的差异,写出通用的代码,可以适应需求的不断变化。
接下来看看我随便写的吃饭的练习:
main.m
//创建一人(Person)类,人类有多种身份如: //学生(Student) //教师(teacher) //老板(boss) //创建一个餐厅(dining),餐厅点菜行为不分身份,只要是人都可以点菜。 #import <Foundation/Foundation.h> #import "Student.h" #import "Boss.h" #import "Teacher.h" #import "Dining.h" int main() { Dining *dining = [Dining new]; Person *stu = [Student new]; [dining doOrder: stu]; Person *tea = [Teacher new]; [dining doOrder:tea]; Person *boss = [Boss new]; [dining doOrder:boss]; return 0; }
Dining.h
#import <Foundation/Foundation.h> #import "Student.h" #import "Boss.h" #import "Teacher.h" @interface Dining : NSObject -(void)doOrder:(Person *)p; @end
Dining.m
#import "Dining.h" @implementation Dining -(void)doOrder:(Person *)p { [p order]; } @end
Teacher.h
#import <Foundation/Foundation.h> #import "Person.h" @interface Teacher : Person -(void)order; @end
Teacher.m
#import "Teacher.h" @implementation Teacher -(void)order { NSLog(@"老师点菜"); } @end
Boos.h
#import <Foundation/Foundation.h> #import "Person.h" @interface Boss : Person -(void)order; @end
Boos.m
#import "Boss.h" @implementation Boss -(void)order { NSLog(@"老板点菜"); } @end
Student.h
#import <Foundation/Foundation.h> #import "Person.h" @interface Student : Person -(void)order; @end
Student.m
#import "Student.h" @implementation Student -(void)order { NSLog(@"学生点菜"); } @end
Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject -(void)order; @end
Person.m
#import "Person.h" @implementation Person -(void)order { NSLog(@"点菜"); } @end