您的位置:首页 > 移动开发 > Objective-C

Objective-C - 继承的经典实例

2015-04-18 13:01 246 查看

继承

/*
 1.继承的好处:
 1> 抽取重复代码
 2> 建立了类之间的关系
 3> 子类可以拥有父类中的所有成员变量和方法

 2.注意点
 1> 基本上所有类的根类是NSObject
 */

/********Animal的声明*******/
@interface Animal : NSObject
{
    int _age;
    double _weight;
}

- (void)setAge:(int)age;
- (int)age;

- (void)setWeight:(double)weight;
- (double)weight;
@end

/********Animal的实现*******/
@implementation Animal
- (void)setAge:(int)age
{
    _age = age;
}
- (int)age
{
    return _age;
}

- (void)setWeight:(double)weight
{
    _weight = weight;
}
- (double)weight
{
    return _weight;
}
@end

/********Dog*******/
// : Animal 继承了Animal,相当于拥有了Animal里面的所有成员变量和方法
// Animal称为Dog的父类
// Dog称为Animal的子类
@interface Dog : Animal
@end

@implementation Dog
@end

/********Cat*******/
@interface Cat : Animal
@end

@implementation Cat
@end

int main()
{
    Dog *d = [Dog new];

    [d setAge:10];

    NSLog(@"age=%d", [d age]);
    return 0;
}


继承下的重写

/*
 1.重写:子类重新实现父类中的某个方法,覆盖父类以前的做法
 2.注意
 1> 父类必须声明在子类的前面
 2> 子类不能拥有和父类相同的成员变量
 3> 调用某个方法时,优先去当前类中找,如果找不到,去父类中找

 2.坏处:耦合性太强
 */

#import <Foundation/Foundation.h>
// Person
@interface Person : NSObject
{
    int _age;
}

- (void)setAge:(int)age;
- (int)age;

- (void)run;

+ (void)test;

@end

@implementation Person

+ (void)test
{
    NSLog(@"Person+test");
}

- (void)run
{
    NSLog(@"person---跑");
}

- (void)setAge:(int)age
{
    _age = age;
}
- (int)age
{
    return _age;
}
@end

// 不允许子类和父类拥有相同名称的成员变量
// Student
@interface Student : Person
{
    int _no;
    // int _age;
}

+ (void)test2;

@end

@implementation Student
// 重写:子类重新实现父类中的某个方法,覆盖父类以前的做法
- (void)run
{
    NSLog(@"student---跑");
}

+ (void)test2
{
    [self test];
}
@end

int main()
{
    [Student test2];

//    Student *s = [Student new];
//    
//    [s run];

    return 0;
}


继承使用场合

/*
1.继承的使用场合
 1> 当两个类拥有相同属性和方法的时候,就可以将相同的东西抽取到一个父类中
 2> 当A类完全拥有B类中的部分属性和方法时,可以考虑让B类继承A类
 A
 {
    int _age;
    int _no;
 }

 B : A
 {
    int _weight;
 }

 // 继承:xx 是 xxx
 // 组合:xxx 拥有 xxx

 2.组合
 A
 {
     int _age;
     int _no;
 }

 B
 {
     A *_a;
     int _weight;
 }
*/

@interface Score : NSObject
{
    int _cScore;
    int _ocScore;
}
@end

@implementation Score
@end

@interface Student : NSObject
{
    // 组合
    Score *_score;
//    int _cScore;
//    int _ocScore;
    int _age;
}
@end

@implementation Student

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: