Objective - C基础: 第二天 - 10.继承的使用场合和组合使用
2015-01-18 16:23
417 查看
在前面, 我们知道了继承的注意事项, 其实继承还有使用的场合, 还有组合的注意事项:
首先我们来说使用场合:
#import <Foundation/Foundation.h>
@interface Score : NSObject
{
int _mathScore;
int _chinaseScore;
}
@end
@implementation Score
@end
@interface Student : NSObject
{
int _mathScore;
int _chinaseScore;
int _age;
}
@end
@implementation Student
@end
int main()
{
return 0;
}
有些人看到这个例子, 第一件事就是看到Student和Score有两个相同的属性, 然后就把Student的两个属性干掉, 把Student直接继承Score, 比如:
#import <Foundation/Foundation.h>
@interface Score : NSObject
{
int _mathScore;
int _chinaseScore;
}
@end
@implementation Score
@end
@interface Student : Score
{
int _age;
}
@end
@implementation Student
@end
int main()
{
return 0;
}
虽然看上去是可以行, 但实际上这是不合理的, Score是分数,
Student是人, 拿一个人去继承分数, 这合理吗?? 人 ≠ 分数, 所以这样子是不行, 我们得找另外一个方法:
@interface Score : NSObject
{
int _mathScore;
int _chinaseScore;
}
@end
@implementation Score
@end
@interface Student : NSObject
{
Score *_score;
int _age;
}
@end
@implementation Student
@end
用一个指针指向于Score, 那么Student也会拥有这两个属性, 而且不会存在不合理, 这个就是组合~~
好了, 这次我们就到这里, 下次我们继续~~~
首先我们来说使用场合:
#import <Foundation/Foundation.h>
@interface Score : NSObject
{
int _mathScore;
int _chinaseScore;
}
@end
@implementation Score
@end
@interface Student : NSObject
{
int _mathScore;
int _chinaseScore;
int _age;
}
@end
@implementation Student
@end
int main()
{
return 0;
}
有些人看到这个例子, 第一件事就是看到Student和Score有两个相同的属性, 然后就把Student的两个属性干掉, 把Student直接继承Score, 比如:
#import <Foundation/Foundation.h>
@interface Score : NSObject
{
int _mathScore;
int _chinaseScore;
}
@end
@implementation Score
@end
@interface Student : Score
{
int _age;
}
@end
@implementation Student
@end
int main()
{
return 0;
}
虽然看上去是可以行, 但实际上这是不合理的, Score是分数,
Student是人, 拿一个人去继承分数, 这合理吗?? 人 ≠ 分数, 所以这样子是不行, 我们得找另外一个方法:
@interface Score : NSObject
{
int _mathScore;
int _chinaseScore;
}
@end
@implementation Score
@end
@interface Student : NSObject
{
Score *_score;
int _age;
}
@end
@implementation Student
@end
用一个指针指向于Score, 那么Student也会拥有这两个属性, 而且不会存在不合理, 这个就是组合~~
好了, 这次我们就到这里, 下次我们继续~~~
相关文章推荐
- Objective - C基础: 第二天 - 9.继承的使用注意
- Objective - C基础: 第二天 - 8.继承的初体验
- Objective - C基础: 第二天 - 7.self使用注意事项
- Objective-C(三、类与继承,基类,self、super关键字,多态,组合)——iOS开发基础
- Python基础(6)- 类和对象(使用、继承、派生、组合、接口、多态、封装、property、staticmethod、classmethod、反射、slots、上下文管理协议、元类)
- [Objective-c 基础 - 2.3] 继承、组合
- Objective - C基础: 第二天 - 11.继承的关键字Super
- [Objective-c 基础 - 2.3] 继承、组合
- 代码复用原则:合理使用类组合和类继承
- Object-C 基础之10 — 使用xml进行归档
- 面向对象设计三大原则(封装变化点,对接口进行编程,多使用组合而不是继承)
- 使用继承还是组合...
- Objective-C 学习笔记(二) 类继承,组合,多态等
- 基础算法测试——生成一个1-10之间的随机整数组合
- C++笔记(10)C++箴言:谨慎使用多继承
- 一些面向对象的设计法则-法则1:优先使用(对象)组合,而非(类)继承
- 【转】使用组合替代继承(面向对象软件设计的“开—闭”原则 )
- 面向对象的设计法则(1)——优先使用(对象)组合,而非(类)继承
- 面向对象的设计法则(1)——优先使用(对象)组合,而非(类)继承
- 面向对象设计三大原则(封装变化点,对接口进行编程,多使用组合而不是继承)