原来学过java,所以OC中的继承和多态就不难理解了。但是OC中却让我对继承和多态有了新的理解.
在OC继承和多态中出现了两个关键词.【开闭原则】和【里氏替换】
在我目前比较肤浅的理解,
开闭原则(OCP)就是扩展,用书上的话来说就是对扩展开放,对修改关闭.简单的说就是我们修改一个软件时
(扩展软件的功能),应该通过扩展的方式来达到软件的扩展,而不是修改原来的代码来实现扩展。
里氏替换原则(LSP) 是面向对象的基本原则之一,是继承复用的基础,
只有衍生类可以替换掉基类,软件单位功能不受影响,基类才能真正被复用,而衍生类也能够在基类的基础上增加新的行为.
如何实现子类的继承呢?
我们可以通过Xcode自动创建,只需要在新建oc类的时候选择父类就好了.
手动的话,把子类.h中#import加入父类.h文件
并且@interface :后面换为父类的类名
之后就可以通过super关键字来调用和重写父类的方法了.
super只能调用方法,也就是消息传递.而不能调用属性.
继承的例子:写一个求正方形和长方形面积和周长的解决方案
实现思路:
创建一个多边形类,MyPloygon,此类中有计算面积和周长的方法area和zhouChang,
继承MyPloygon类创建正方形类Square,并重写父类的area和zhouChang方法。
继承MyPloygon类创建正方形类Rectangular,并重写父类的area和zhouChang方法.
创建Accounrer ,并实现计算方法calculate.
我创建的类文件如下
运行后结果为:
Main方法为:
#import <Foundation/Foundation.h>
#import "Square.h"
#import "Accounter.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Square *sq = [[Square alloc]initWithWidth:5.0];
Rectangular *rec = [[Rectangular alloc]initWithWidth:5 andH:10];
// [sq area];
// [sq zhouChang];
Accounter *acc = [[Accounter alloc]init];
[acc calculate:sq];
[acc calculate:rec];
}
return 0;
}
MyPloygon .h:
#import <Foundation/Foundation.h>
@interface MyPloygon : NSObject
-(void)area;
-(void)zhouChang;
@end
MyPloygon.m:
#import "MyPloygon.h"
@implementation MyPloygon
- (void)area
{
NSLog(@"计算面积:");
}
-(void)zhouChang
{
NSLog(@"计算周长:");
}
@end
Rectangular.h
#import "MyPloygon.h"
@interface Rectangular : MyPloygon
@property double height;
@property double width;
-(id)initWithWidth:(double)w andH:(double)h;
@end
Rectangular.m
#import "Rectangular.h"
@implementation Rectangular
-(id)initWithWidth:(double)w andH:(double)h
{
if(self = [super init])
{
_width = w;
_height = h;
}
return self;
}
-(void)area
{
[super area];
double area = _width *_height;
NSLog(@"长方形面积为:%.2f",area);
}
-(void)zhouChang
{
[super zhouChang];
double zhouc = (_width + _height) * 2;
NSLog(@"长方形周长为:%.2f",zhouc);
}
@end
Square.h
#import "MyPloygon.h"
@interface Square : MyPloygon
{
double width;
}
-(id)initWithWidth:(double)_width;
@end
Square.m
#import "Square.h"
@implementation Square
-(id)initWithWidth:(double)_width
{
if(self= [super init])
{
width = _width;
}
return self;
}
-(void)area
{
[super area];
double area = width * width;
NSLog(@"正方形面积为:%.2f",area);
}
-(void)zhouChang
{
[super zhouChang];
double zhouc = width * 4;
NSLog(@"正方形的周长为:%.2f",zhouc);
}
@end
Accounter.h
#import <Foundation/Foundation.h>
#import "Square.h"
#import "Rectangular.h"
@interface Accounter : NSObject
-(void)calculate:(id)p;
@end
Accounter.m
#import "Accounter.h"
@implementation Accounter
-(void)calculate:(id)p
{
[p area];
[p zhouChang];
}
@end