iOS继承和多态
在iOS开发中,继承(Inheritance)和多态(Polymorphism)是面向对象编程的两个核心概念。
1.继承:
继承是面向对象编程中代码复用的一种手段。在iOS中,可以通过:来继承一个类。
// 父类
@interface ParentClass : NSObject
- (void)parentMethod;
@end
@implementation ParentClass
- (void)parentMethod {
NSLog(@"Parent method called");
}
@end
// 子类
@interface ChildClass : ParentClass
- (void)childMethod;
@end
@implementation ChildClass
- (void)childMethod {
NSLog(@"Child method called");
}
@end
在上述代码中,ChildClass继承了ParentClass,因此ChildClass拥有ParentClass的所有方法和属性。
2.多态:
多态是指一个接口多种实现,可以在运行时动态绑定实现。在iOS中,多态通常通过方法重写(Override)和方法重载(Overload)来实现。
// 父类
@interface ParentClass : NSObject
- (void)commonMethod;
@end
@implementation ParentClass
- (void)commonMethod {
NSLog(@"Parent commonMethod");
}
@end
// 子类
@interface ChildClass : ParentClass
- (void)commonMethod;
@end
@implementation ChildClass
- (void)commonMethod {
NSLog(@"Child commonMethod");
}
@end
// 使用
ParentClass *parent = [[ParentClass alloc] init];
[parent commonMethod]; // 输出:Parent commonMethod
ChildClass *child = [[ChildClass alloc] init];
[child commonMethod]; // 输出:Child commonMethod
在上述代码中,ParentClass和ChildClass都有一个名为commonMethod的方法,但是它们的实现是不同的。当我们创建ParentClass和ChildClass的实例并调用commonMethod方法时,会根据实例的实际类型调用相应的方法实现。这就是多态。
注意:在Objective-C中,多态不仅仅是方法重写,还可以通过对象的类型来判断应该调用哪个方法实现,这是动态绑定的结果。