OC-继承

一、继承

  1. 继承的好处:

    1> 抽取了重复代码

    2> 建立了类与类之间的联系

  2. 子类可以拥有父类中的所有成员变量和方法

eg:

#import <Foundation.Foundation.h>


@interface Animal : NSObject //声明一个Animal类,并且继承了NSObject
{
    int _age; // 声明了两个成员变量
    double _weight;
}
- (void)setAge:(int)age; //声明set方法
- (void)setWeight:(double)weight;
- int)age;  //声明get方法
- (double)weight;
- (void)run;


@implementation Animal //类的实现
- (void)setAge:(int)age //set方法的实现
{
    _age = age;
}

- (void)setWeight:(double)weight//set方法的实现
{
    _weight = weight;
}

- int)age //get方法的实现
{
    return _age;
}

- (double)weight //get方法的实现
{
    return _weight;
}

- (void)run
{
    NSLog(@"动物跑了起来");
}
@end





@interface Dog : Animal //Dog继承了Animal里面所有的成员变量和方法


@end


@implementation Dog

@end

int main()
{
    Dog *d = [Dog new];
    [d setAge:8];
    [d setWeight:20.0];
    NSLog(@"%岁的狗,%d公斤",[d age], [d weight]);
    
    return 0;
}
  1. 基本上所有类的根类都是NSObject

  2. 注意点:

(1)不允许子类和父类拥有相同的成员变量

(2)父类放在子类之前声明

(3)子类和父类允许有相同的方法

(4)调用某个对象的方法时,优先去当前类中找,如果找不到,再去父类中找

(5)子类重新实现父类的某个方法,会覆盖父类以前的方法
5.重写
子类重新实现父类中某个方法,覆盖父类以前的做法
eg:

#import <Foundation.Foundation.h>


@interface Animal : NSObject //声明一个Animal类,并且继承了NSObject
{
    int _age; // 声明了两个成员变量
    double _weight;
}
- (void)setAge:(int)age; //声明set方法
- (void)setWeight:(double)weight;
- int)age;  //声明get方法
- (double)weight;
- (void)run;


@implementation Animal //类的实现
- (void)setAge:(int)age //set方法的实现
{
    _age = age;
}

- (void)setWeight:(double)weight//set方法的实现
{
    _weight = weight;
}

- int)age //get方法的实现
{
    return _age;
}

- (double)weight //get方法的实现
{
    return _weight;
}

- (void)run
{
    NSLog(@"动物跑了起来");
}
@end





@interface Dog : Animal //Dog继承了Animal里面所有的成员变量和方法

- (void)run;
@end


@implementation Dog
- (void)run //重写父类run方法
{
    NSLog(@"%岁,%d公斤的狗跑了起来",[d age], [d weight]);    
}

@end

int main()
{
    Dog *d = [Dog new];
    [d setAge:8];
    [d setWeight:20.0];
    [d run];
    NSLog(@"%岁的狗,%d公斤",[d age], [d weight]);
    
    return 0;
}

  1. 每个类中都有一个superclass指针指向父类

  2. 继承的缺点:耦合性太强(类与类之间的关系过于紧密)

8 继承和组合

   继承:XX 是XXX

   组合:XX拥有XXX (格式 : score  *_score)

9.继承的使用场合

 它的所有属性都是你想要的,一般就继承

 它的部分属性是你想要的,可以抽取出另一个父类

super关键字

1> 可以直接调用父类中的方法

2> super处在对象方法中,就会调用父类的对象方法。处在类方法中,那么就会调用父类的类方法

3> 适用场合:子类重写父类的方法时想保留父类的一些行为

posted @ 2015-07-09 07:18  wlv587  阅读(136)  评论(0编辑  收藏  举报