二、 继承
1、继承就是子类拥有父类的所有属性和方法,这样做可以抽取重用的代码,减少代码量,使程序更精简。只需在类名后加上冒号,跟上需要继承的类名即可。
继承不可以随便使用,不能仅因为一个类的成员是另一个类成员的子集,而简单将其定义成子类,例如:
@interface Score:NSObject
{
int _cScore;
int _ocScore;
}
@end
@implementation Score
@end
@interface Student:Score
{
//int _cScore;
//int _ocScore;
int _age;
}
@end
@implementation Student
@end
这里的成绩类有两个属性,与学生类的其中两个属性一样,但是两个类没有继承的关系,不能说“学生”是一个“分数”,所以这种情况不应该用继承,而是用“组合”。如下:
@interface Score:NSObject
{
int _cScore;
int _ocScore;
}
@end
@implementation Score
@end
@interface Student:NSObject
{
//组合
Score *score;//把Score变成Student的一部分
int _age;
}
@end
@implementation Student
@end
所以如果两个类是“一个是另一个”的关系,用继承;而若是“一个类拥有另一个类”则用组合。
2、如果在子类中想调用父类的同名方法,需要用到super关键字,例如:
#import <Foundation/Foundation.h>
@interface Zombie:NSObject
- (void)walk;
@end
@implementation Zombie
- (void)walk
{
NSLog(@"往前挪两步----");
}
@interface JumpZombie:Zombie
@end
@implementation JumpZombie
- (void)walk
{
//跳两下
NSLog(@"跳两下----");
//走两下
[super walk];//调用父类的walk方法
}
@end
int main()
{
JumpZombie *jz = [JumpZombie new];
[jz walk];
return 0;
}
1、继承就是子类拥有父类的所有属性和方法,这样做可以抽取重用的代码,减少代码量,使程序更精简。只需在类名后加上冒号,跟上需要继承的类名即可。
继承不可以随便使用,不能仅因为一个类的成员是另一个类成员的子集,而简单将其定义成子类,例如:
@interface Score:NSObject
{
int _cScore;
int _ocScore;
}
@end
@implementation Score
@end
@interface Student:Score
{
//int _cScore;
//int _ocScore;
int _age;
}
@end
@implementation Student
@end
这里的成绩类有两个属性,与学生类的其中两个属性一样,但是两个类没有继承的关系,不能说“学生”是一个“分数”,所以这种情况不应该用继承,而是用“组合”。如下:
@interface Score:NSObject
{
int _cScore;
int _ocScore;
}
@end
@implementation Score
@end
@interface Student:NSObject
{
//组合
Score *score;//把Score变成Student的一部分
int _age;
}
@end
@implementation Student
@end
所以如果两个类是“一个是另一个”的关系,用继承;而若是“一个类拥有另一个类”则用组合。
2、如果在子类中想调用父类的同名方法,需要用到super关键字,例如:
#import <Foundation/Foundation.h>
@interface Zombie:NSObject
- (void)walk;
@end
@implementation Zombie
- (void)walk
{
NSLog(@"往前挪两步----");
}
@interface JumpZombie:Zombie
@end
@implementation JumpZombie
- (void)walk
{
//跳两下
NSLog(@"跳两下----");
//走两下
[super walk];//调用父类的walk方法
}
@end
int main()
{
JumpZombie *jz = [JumpZombie new];
[jz walk];
return 0;
}