黑马程序员技术交流社区
标题:
talk is cheap, show me the code!--面向对象三大特性之——继承
[打印本页]
作者:
崔石炫
时间:
2014-10-22 00:08
标题:
talk is cheap, show me the code!--面向对象三大特性之——继承
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject //人类,用有年龄属性
{
int _age;
}
- (void)setAge:(int)age;
- (int)age;
@end
复制代码
Person.m
#import "Person.h"
@implementation Person
- (void)setAge:(int)age
{
if(age > 0)
{
_age = age;
}
}
- (int)age
{
return _age;
}
@end
复制代码
Score.h
#import <Foundation/Foundation.h>
@interface Score : NSObject //分数类
{
int _CScore; //C语言成绩
int _OCScore; //OC成绩
}
- (void)setCScore:(int)CScore;
- (int)CScore;
- (void)setOCScore:(int)OCScore;
- (int)OCScore;
@end
复制代码
Score.m
#import "Score.h"
@implementation Score
- (void)setCScore:(int)CScore
{
if(CScore >= 0)
{
_CScore = CScore;
}
}
- (int)CScore
{
return _CScore;
}
- (void)setOCScore:(int)OCScore
{
if(OCScore >= 0)
{
_OCScore = OCScore;
}
}
- (int)OCScore
{
return _OCScore;
}
@end
复制代码
Student.h
#import "Person.h"
#import "Score.h"
@interface Student : Person //学生类Student,继承自人类Person,组合了分数属性Score
{
Score *_score;
}
- (void)setScore:(Score *)score;
- (Score *)score;
@end
复制代码
Student.m
#import "Student.h"
@implementation Student
- (void)setScore:(Score *)score
{
_score = score;
}
- (Score *)score
{
return _score;
}
@end
复制代码
main.m
/*
继承:
@interface 子类名 : 父类名
//成员变量、方法的声明
@end
* 子类继承了父类,就相当于拥有了父类中声明的所有成员变量和方法,父类的属性和方法可以在子类中访问
* 通常将多种相似的对象具有的共同特征提取到父类中
继承、组合的合理使用:
继承:子类是父类的一种,比如说Student是Person
组合:对象拥有某种属性,比如说Student拥有Score类型的属性
如果Student类继承Score类,再组合一个Person属性,也能实现功能,但是不合常理。
*/
#import <Foundation/Foundation.h>
#import "Score.h"
#import "Person.h"
#import "Student.h"
int main(int argc, const char * argv[])
{
Score *sco = [Score new];
[sco setCScore:99];
[sco setOCScore:88];
Student *s = [Student new];
[s setAge:22];
[s setScore:sco];
NSLog(@"_age = %d , _CScore = %d , _OCScore = %d" , [s age] , [[s score] CScore] , [[s score] OCScore]); //子类访问父类的_age属性
//输出:_age = 22 , _CScore = 99 , _OCScore = 88
return 0;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2