深入浅出Objective-C笔记(五)

2015-11-19  本文已影响31人  无聊的呆子

类的继承


圆形类

@interface Circle : NSObject
{
  double x;
  double y;
  CGColorRef lineColor;
  CGColorRef fillColor;

  double radius;
}

- (void)moveToX:(double)x Y:(double)y;
- (void)setLineColor:(CGColorRef)lineColor;
- (void)setFillColor:(CGColorRef)fillColor;

- (void)setRadius:(double)r;
@end 

矩形类

@interface Rectangle : NSObject
{
  double x;
  double y;
  CGColorRef lineColor;
  CGColorRef fillColor;

  double width;
  double height;
}

- (void)moveToX:(double)x andY:(double)y;
- (void)setLineColor:(CGColorRef)lineColor;
- (void)setFillColor:(CGColorRef)fillColor;

- (void)setWidth:(double)w;
- (void)setHeight:(double)h;
@end

对比圆形类跟矩形类,发现有很多重复的部分。

** 继承反映的是类之间的相似性 **

形状类

@interface Shape : NSObject
{
  double x;
  double y;
  CGColorRef lineColor;
  CGColorRef fillColor;
}

- (void)moveToX:(double)x andY:(double)y;
- (void)setLineColor:(CGColorRef)lineColor;
- (void)setFillColor:(CGColorRef)fillColor;

@end 

如果类B继承了类A,那么B会包含A的所有属性和方法。

如果圆形类和矩形类都继承了形状类,那么很多属性跟方法就不用再写一遍。

  @interface Circle : Shape
  {
      double radius;
  }
  - (void)setRadius:(double)r;
  @end

  Circle类继承了Shape类,代码精简了很多,重复的部分都不用写了。
  @interface Rectangle : Shape
  {
    double width;
    double height;
  }
  - (void)setWidth:(double)w;
  - (void)setHeight:(double)h;
  @end    
  
  使用继承,只要写自己类特有的属性跟方法即可。

父类Shape类
#import <Foundation/Foundation.h>

  @interface Shape : NSObject {
        double xCoord;
        double yCoord;
        CGColorRef lineColor;
        CGColorRef fillColor;
  }

  - (void)moveToX:(double)x andY:(double)y;
  - (void)setLineColor:(CGColor)lineColor;
  - (void)setFillColor:(CGColor)fillColor;

  @end 

  @implementation Shape
   -(id)init {
        self = [super init];
        if (self) {
            xCoord = 0.0;
            yCoord = 0.0;
            lineColor = NULL;
            fillColor = NULL;
        }
        return self;
  }

  - (void)moveToX:(double)x andY:(double)y {
      xCoord = x;
      yCoord = y;
  }

  - (void)setLineColor:(CGColor)color {
      lineColor = color;
  }

  - (void)setFillColor:(CGColor)color {
      fillColor = color;
  }

  @end 

子类Circle类

@interface Circle : Shape {
    double radius;
}

- (void)setRadius:(double)r;
@end

@implementation Circle {
- (id)init {
    self = [super init];//注意,因为继承自Shape类,所以这里的super指的是Shape类
    if (self) {
        radius = 0.0;//只用初始化Circle类特有的半径变量
    }
    return self;
}

- (void)setRadius:(double)r {
      radius = r;
}
@end 

子类Rectangle类

@interface Rectangle : Shape {
    double width;
    double height;
}
- (void)setWidth:(double)w;
- (void)setHeight:(double)h;
@end

@implementation Rectangle {
- (id) init {
    self = [super init];//实现部分不要忘了第一步是初始化!
    if (self) {
        width = 0.0;
        height = 0.0;
    }
    return self;
}
- (void)setWidth:(double)w {
    width = w;
}
- (void)setHeight:(double)h {
    height = h;
}
@end 
上一篇下一篇

猜你喜欢

热点阅读