继承

 

#import <Foundation/Foundation.h>

/*

 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

 

 

 

 

 

/*

 

 1.重写:子类重新实现父类中的某个方法,覆盖父类以前的做法

 

 2.注意

 

 1> 父类必须声明在子类的前面

 

 2> 子类不能拥有和父类相同的成员变量

 

 3> 调用某个方法时,优先去当前类中找,如果找不到,去父类中找

 

 

 

 2.坏处:耦合性太强

 

 

 

/*

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;

 }

*/

 

 

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

 

}

 

posted @ 2016-03-28 10:49  lance.xiang  阅读(98)  评论(0)    收藏  举报