创建: 2018/01/21
动态结合(多态) | |
动态结合 |
呼出同一个方法,根据呼出方不同执行的处理也不同
//--------------------------------------------------------------------- // 类型定义 //--------------------------------------------------------------------- //动态结合与多态 @interface S4_A : NSObject { } - (void)getLocationOfHierarchy; - (void)getLocationOfHierarchy:(BOOL)isneedHello; @end @interface S4_B : S4_A { } - (void)getLocationOfHierarchy; //重载 - (void)getLocationOfHierarchy:(BOOL)isneedHello; //重载 @end //--------------------------------------------------------------------- // 类定义 //--------------------------------------------------------------------- //动态结合与多态 @implementation S4_A - (void)getLocationOfHierarchy { puts("this is A"); } - (void)getLocationOfHierarchy:(BOOL)isneedHello { if (isneedHello) { puts("hello, this is A"); } else { puts("need no hello, this is A"); } } @end @implementation S4_B - (void)getLocationOfHierarchy { puts("this is B"); } - (void)getLocationOfHierarchy:(BOOL)isneedHello { if (isneedHello) { puts("hello, this is B"); } else { puts("need no hello, this is B"); } } @end //--------------------------------------------------------------------- // 测试函数 //--------------------------------------------------------------------- void S4Tester(void) { puts("-----------------------------------------"); puts(" S4"); puts("-----------------------------------------"); id aTemp = [[S4_A alloc] init]; [aTemp getLocationOfHierarchy]; [aTemp getLocationOfHierarchy:NO]; [aTemp getLocationOfHierarchy:YES]; id bTemp = [[S4_B alloc] init]; [bTemp getLocationOfHierarchy]; [bTemp getLocationOfHierarchy:NO]; [bTemp getLocationOfHierarchy:YES]; } 运行结果 ----------------------------------------- S4 ----------------------------------------- this is A need no hello, this is A hello, this is A this is B need no hello, this is B hello, this is B Program ended with exit code: 0
|
多态 |
多态就是动态结合 优点: 不用对每一个具体对象改变现有代码 p60 |
数据类型与类 | |
编程的类型声明 | |
实例变量的封装 |
|
类对象 (class object) | |