Objective 多态

时间:2023-03-09 18:09:25
Objective 多态

多态的特点

1、没有继承就没有多态

2、代码的体现:父类类型的指针指向子类对象

3、好处:如果函数方法参数中使用的是父类类型,则可以传入父类和子类对象,而不用再去定义多个函数来和相应的类进行匹配了。

4、局限性:父类类型的变量不能直接调用子类特有的方法,如果必须要调用,则必须强制转换为子类特有的方法。

Graphics(图形)的类声明

 @interface Graphics : NSObject
-(void)prin;
@end

Graphics(图形)的类实现

@implementation Graphics
-(void)prin
{
NSLog(@"打印图形的面积");
}
@end

Triangle(三角形)、Rectangular(矩形)的类实现,在这里对三角形和矩形的prin方法进行了重写,不需要在声明,直接实现,

 @interface Rectangular : Graphics

 @end
 @interface Triangle : Graphics

 @end
@implementation Triangle
-(void)prin //方法重写
{
NSLog(@"打印三角形的面积");
}
@end
@implementation Rectangular

-(void)prin //方法重写
{
NSLog(@"打印矩形的面积");
}
@end

下面定义一个People(人)的类,在其中实现了多态,其中矩形和三角形都为图形,Graphics *指向子类的对象在这里实现了代码的简化(矩形和三角形继承了图形)。

简而言之,多态就相当于C语言中的具有形参的函数,就像下面代码中的c,c是一个Graphics(图形)的指针类型,那么Triangle(三角形)、Rectangular(矩形)的对象就都可以传入进来。调用的时候直接改变参数就可以了

@implementation People

-(void)calculate:(Graphics *)c
{
[c prin];
}
@end

主程序代码如下

 #import "Graphics.h"
#import "People.h"
#import "Triangle.h"
#import "Rectangular.h"
#import "Circular.h" int main(int argc, const char * argv[]) {
@autoreleasepool
{
Triangle *triangle = [[Triangle alloc] init]; //Triangle(三角形)类型指针指向Triangle类型对象
[triangle prin]; //Triangle类对象调用对象方法 //多态
//父类指针指向子类对象
Graphics *graphics = [[Rectangular alloc] init];
//注意这里调用的是哪个方法
[graphics prin]; //动态监测--调用方法时会检测对象的真实性
//注意:父类类型的指针变量不能直接调用子类特有的方法(prin是共有的)
Graphics *graphics1 = [[Graphics alloc] init];
[graphics1 prin];
NSLog(@"-------");
Circular *circular = [[Circular alloc] init];
People *people = [[People alloc] init];
[people calculate:graphics];
[people calculate:triangle];
[people calculate:circular];
}
return ;
}