09-多态
三大特性最后一个:多态(多种形态)
1、多态的基本使用
要想有多态,必须先有继承。没有继承就没有多态。
多态:父类指针指向子类对象。
创建两个类:Student类 和 Person类 ,并且Student类 继承 Person类
1 /* 2 创建两个类:Student类 和 Person类 ,并且Student类 继承 Person类 3 */ 4 #import <Foundation/Foundation.h> 5 6 //Person类 7 @interface Person : NSObject 8 - (void)run; 9 @end 10 11 @implementation Person 12 - (void)run 13 { 14 NSLog(@"Person----跑"); 15 } 16 @end 17 18 @interface Student : Person 19 - (void)run; 20 @end 21 //Student类 22 @implementation Student 23 //重写run方法 24 - (void)run 25 { 26 NSLog(@"Student----跑"); 27 } 28 @end 29 int main(int argc, const char * argv[]) 30 { 31 //多种形态 32 //Student *stu = [Student new]; //对象是Student类型(形态1) 33 //父类指针指向子类对象,就是多态 34 Person *p = [Student new];//对象是Person类型(形态2) 35 //调用方法时会检测对象的真实形态 36 [p run]; 37 return 0; 38 }
(1)第34行,表示将Student类的对象地址给了,Perosn类型的指针变量。这时,父类指针指向了子类对象,便是多态。
(2)调用方法的时候,会自动检测对象的真实形态,这里对象的真实形态为Student类型,于是就调用Student类中的run方法,而不是Person类中的run方法。
输出结果是: Student----跑
2、多态使用的注意点
Student *stu = [Person new]; Person 不是 Student
Nsstring *s = [Cat new]; Cat 不是 NSString(字符串)
Cat *c = [Animal new]; Animal 不是 Cat
上面的几种写法,都不符合逻辑,但是由于OC的弱语法,编译器不会报错,只是一个警告。
但是不推荐这么写,这么写造成代码可读性差,逻辑混乱。
3、使用多态的好处
如果函数的参数是父类指针,那么子类对象都可以传递给函数的参数。
人生之路,不忘初心,勿忘始终!