类的继续可以加快代码的构建,建立类的关系,使得程序员可以用面向对象的思维模式处理计算机数据问题,
继承使用中要注意以下几点
1,子类中不能声明和父类中同名的成员变量
2, 调用的方法如果在当前类中没有声明和实现,则会在运行时向父类的类信息中进行查找,如果父类中也没有,则会继续向父类的父类信息中去查找。。。
3, 父类必须声明在子类的前边
#import <Foundation/Foundation.h>
// Person类
@interface Person : NSObject
{
int _age;
float _weight;
}
- (void)setAge: (int)age;
- (void)setWeight: (float)weight;
- (void)run;
@end
// Teacher类
@interface Teacher : Person
{
float _heigh;
// int _age; 不可以声明和父类中同名的成员变量
}
- (void)setHeigh: (float)heigh;
@end
int main()
{
Teacher *t = [Teacher new];
[t setAge:33];
[t setWeight:55];
[t setHeigh:1.78];
[t run];
return 0;
}
// Person 实现
@implementation Person
- (void)run
{
NSLog(@"Person ---- run");
}
- (void)setAge:(int)age
{
_age = age;
}
- (void)setWeight:(float)weight
{
_weight = weight;
}
@end
// Teacher 实现
@implementation Teacher
- (void)setHeigh:(float)heigh
{
_heigh = heigh;
}
// 在子类中声明和实现父类中的同名方法 称之为重写
- (void)run
{
NSLog(@"Teaher ---- run!");
}
@end