浅谈Objective-C中的继承

浅谈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


在SSShape.m中实现方法

#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];
    }
}

到此,就实现了子类继承父类。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值