1.继承
#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;
}
2.继承的使用注意
/*
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;
}
3.组合的使用
/*
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
4.super的使用
/*僵尸跳跃僵尸、舞王僵尸、铁桶僵尸 */#import <Foundation/Foundation.h>/*super的作用1.直接调用父类中的某个方法2.super处在对象方法中,那么就会调用父类的对象方法super处在类方法中,那么就会调用父类的类方法3.使用场合:子类重写父类的方法时想保留父类的一些行为*/// 僵尸@interface Zoombie : NSObject- (void)walk;+ (void)test;- (void)test;@end@implementation Zoombie- (void)walk{NSLog(@"往前挪两步******");}+ (void)test{NSLog(@"Zoombie+test");}- (void)test{NSLog(@"Zoombie-test");}@end// 跳跃僵尸@interface JumpZoombie : Zoombie+ (void)haha;- (void)haha2;@end@implementation JumpZoombie+ (void)haha{[super test];}- (void)haha2{[super test];}- (void)walk{// 跳两下NSLog(@"跳两下");// 走两下(直接调用父类的walk方法)[super walk];//NSLog(@"往前挪两步----");}@endint main(){//[JumpZoombie haha];JumpZoombie *jz = [JumpZoombie new];[jz haha2];return 0;}