为什么要封装
# import <Foundation/Foundation.h>
@interface Student : NSObject
{
// 成员变量尽量不要用@public
// @public
int age;
// 只读(readonly):只允许外界访问我的no,不允许外界修改我的mo
int no; // 只需要提供get方法
}
- (void) study;
/*
1.作用:提供一个方法给外界设置age属性值,可以在方法里面对参数进行相应过滤
2.命名规范:
1> 方法名必须以set开头
2> set后面跟上成员变量的名称,成员变量的首字母必须大写
3> 返回值一定时void
4> 一定要接收一个参数,而且参数类型跟成员变量类型一致
5> 行参的名称不能跟成员变量名一样
*/
- (void) setAge:(int)newAge;
/*
get方法
1.作用:返回对象内部的成员变量
2.命名规范:
1> 肯定有返回值, 返回值类型肯定与成员变量类型一致
2> 方法名跟成员变量名一致
3> 不需要接收任何参数
*/
- (int)age;
@end
@implementation Student
// set方法的实现
- (void) setAge:(int)newAge
{
// 对传进来的参数进行过滤
if(newAge <= 0) {
newAge = 1;
}
age = newAge;
}
- (int) age
{
return age;
}
- (void) study
{
NSLog(@"%d岁的人在学习", age);
}
@end
int main()
{
Student *stu = [Student new];
// stu -> age = 10;
[stu setAge:-10];
[stu study];
NSLog(@"学生的年龄为:%d岁", [stu age]);
return 0;
}
封装的细节
# import <Foundation/Foundation.h>
typedef enum {
sexMan,
sexWoman
}Sex;
@interface Student : NSObject
{
/*
成员变量的命名规范:一定要以下划线 _ 开头
作用:
1.让成员变量和get方法名称区分开
2.可以跟局部变量去分开,一看到下划线开头的变量,一般都是成员变量
*/
int _no;
int _sex;
}
- (void)setSex:(int)sex;
- (Sex)sex;
- (void)setNo:(int)no;
- (int)no;
@end
@implementation Student
// sex的set和get方法
- (void)setSex:(int)sex
{
_sex = sex;
}
- (Sex)sex
{
return _sex;
}
// no的set和get方法
- (void)setNo:(int)no
{
_no = no;
}
- (int)no
{
return _no;
}
@end
int main()
{
Student *stu = [Student new];
[stu setNo:1212036];
[stu setSex:sexMan];
NSLog(@"该学生是%d的,学号是:%d", [stu sex], [stu no]);
return 0;
}
封装的练习
/*
4.设计一个成绩类
* C语言成绩(可读可写)
* OC成绩(可读可写)
* 总分(只读)
* 平局分(只读)
*/
# import <Foundation/Foundation.h>
@interface Score : NSObject
{
double _cScore; //C语言成绩
double _ocScore; //OC成绩
double _totalScore; //总分
double _averageScore; //平均分
}
- (void)setCScore:(double)cScore;
- (double)cScore;
- (void)setOcScore:(double)ocScore;
- (double)ocScore;
//总分
- (double)totalScore;
//平均分
- (double)averageScore;
@end
@implementation Score
//C语言的set和get方法
- (void)setCScore:(double)cScore
{
_cScore = cScore;
//总分
_totalScore = _cScore + _ocScore;
//平均分
_averageScore = _totalScore / 2;
}
- (double)cScore
{
return _cScore;
}
//OC语言的set和get方法
- (void)setOcScore:(double)ocScore
{
_ocScore = ocScore;
//总分
_totalScore = _cScore + _ocScore;
//平均分
_averageScore = _totalScore / 2;
}
- (double)ocScore
{
return _ocScore;
}
//总分的get方法
- (double)totalScore
{
return _totalScore;
}
//平均分分的get方法
- (double)averageScore
{
return _averageScore;
}
@end
int main()
{
Score *s = [Score new];
[s setCScore:80];
[s setOcScore:75];
NSLog(@"C语言的成绩是:%5.2f, OC成绩是:%5.2f, 总分是:%5.2f, 平均分是:%5.2f", [s cScore], [s ocScore], [s totalScore], [s averageScore]);
return 0;
}