浅谈Objective-C 中的继承:
继承是为了解决代码重复的问题,有时候在写代码时,我们会重复写很多代码,这时我们抽象出来一个类作为父类,把这段重复的代码写到父类里面,如下图:
现在来实现它:
首先建一个公共头文件common.h
#ifndef composition_common_h
#define composition_common_h
//图形颜色
typedef enum{
kRed,
kGreen,
KBlue
}ShapeColor;
//图形类型
typedef enum{
kCircle,
KRectangle,
KEgg
} ShapeType;
//图形区域
typedef struct{
int x;
int y;
int width;
int height;
} ShapeRect;
#endif
我们需要建一一个父类,Shape,和两个子类Circle,Rectangle
在SSShape.h中声明方法和成员变量
#import <Foundation/Foundation.h>
#import "common.h"
@interface SSShape : NSObject
{
ShapeColor fillcolor;
ShapeRect bounds;
}
-(void)setFillColor:(ShapeColor)color;
-(void)setBounds:(ShapeRect)rect;
-(NSString *)colorName;
-(void)draw;
@end
#import "SSShape.h"
@implementation SSShape
-(void)setFillColor:(ShapeColor)color
{
fillcolor = color;
}
-(void)setBounds:(ShapeRect)rect
{
bounds =rect;
}
-(NSString *)colorName
{
NSString *name = nil;
switch (fillcolor) {
case kRed:
name = @"red";
break;
case kGreen:
name = @"green";
break;
case KBlue:
name = @"blue";
break;
default:
break;
}
return name;
}
-(void)draw
{
}
@end
在Circle.m和rectangle.m中只需实现draw方法
#import "Circle.h"
@implementation Circle
//画图
-(void)draw
{
NSLog(@"circle at[%d,%d,%d,%d],color is %@",bounds.x,bounds.y,bounds.width,bounds.height,
[self colorName]);
}
@end
在main.m中需要这样实现
#import <Foundation/Foundation.h>
#import "common.h"
#import "SSShape.h"
#import "Circle.h"
#import "Egg.h"
#import "rectangle.h"
extern void drawShapes(SSShape *shapes[],int num);
int main(int argc, const char * argv[])
{
//利用父类定义一个数组,来存储三个图形对象
SSShape *shapes[2];
//创建Circle对象
Circle *cirle = [Circle new];
ShapeRect circleRect={0,0,20,20};
[cirle setFillColor:kRed];
[cirle setBounds:circleRect];
//将circle对象放到数组的第一个元素位置
shapes[0] = cirle;
//创建rectangle对象
rectangle *rect = [rectangle new];
[rect setFillColor:kGreen];
ShapeRect rectRect={20,20,40,40};
[rect setBounds:rectRect];
//将rectangle对象放到数组的第二个元素位置
shapes[1] = rect;
//调用绘制图形的方法
drawShapes(shapes, 2);
return 0;
}
//画图的总控方法
void drawShapes(SSShape *shapes[],int num)
{
for (int i = 0; i < num; i++) {
[shapes[i] draw];
}
}
到此,就实现了子类继承父类。