面向对象的三大特征:封装、继承、多态
1.封装
什么是封装:在程序上,隐藏对象的属性和实现细节,仅对外公开接口,控制在程序中属性的读和修改的访问级别;将对象得到的数据和行为(或功能)相结合,形成一个有机的整体,也就是将数据与操作数据的源代码进行有机的结合,形成“类”,其中数据和函数都是类的成员。
1> set方法
① 作用:提供一个方法给外界设置成员变量值,实现对参数的相应过滤
② 命名规范
*方法名必须以set开头
*set后面跟上成员变量的名称,成员变量名首字母必须大写
*返回值一定是void
*一定要接收一个参数,而且参数类型跟成员变量类型一致
*形参的名称不能跟成员变量名一样
eg:
#import <Foundation.foundation.h>@interface Student : NSObject : NSObject //声明一个类
{int _age;//设置一个成员变量
}- (void)study;//声明一个study对象方法
- (void)setAge:(int)age;//声明set方法@end@implementation Student //对声明的方法进行实现- (void)setAge:(int)age //set方法的实现
{if(age <= 0) //对不合理的值进行过滤{age = 1;}_age = age;
}- (void)study //study方法的实现
{NSLog("%d岁的学生在学习",age);
}@endint main()
{Student *stu = [Student new];//新建一个Student类型对象[stu setAge :10];//调用set方法进行赋值操作[stu study];// 对象调用对象方法return 0;
}
2> get方法
①作用:返回成员变量值
②命名规范
*有返回值,返回值类型与成员变量类型相同
*方法名跟成员变量名相同
*不需要接收任何参数
eg:
#import <Foundation.foundation.h>@interface Student : NSObject //声明一个类
{int _age;//设置一个成员变量
}- (void)study;//声明一个对象方法
- (void)setAge:(int)age;//声明set方法
- (int)age;//声明get方法@end@implementation Student //对声明的方法进行实现- (void)setAge:(int)age //set方法的实现
{if(age <= 0) //对不合理的值进行过滤{age = 1;}_age = age;
}- (int)age // get方法的实现
{return _age;
}- (void)study //study方法的实现
{NSLog("%d岁的学生在学习",[stu age]);//get方法的调用
}@endint main()
{Student *stu = [Student new];//新建一个Student类型对象[stu setAge :10];//调用set方法进行赋值操作[stu study];// 对象调用对象方法return 0;
}
3> 封装细节
①成员变量名以_开头,命名规范
*作用1,让成员变量名与get方法名区分开
*作用2,跟局部变量名分开,带_一般就是成员变量名
eg:
#import <Foundation.Foundation.h>@interface Score : NSObject //声明Score类
{int _cScore;//设置成员变量 _cScoreint _ocScore;//设置成员变量 _ocScoreint _totalScore;//设置成员变量 _totalScoreint _averageScore;//设置成员变量 _averageScore
}- (void)setCScore:(int)cScore;//声明set方法
- (int)cScore;//声明get方法- (void)setOcScore:(int)ocScore;//声明set方法
- (int)ocScore;//声明get方法- (int)totalScore;//声明get方法
- (int)averageScore;//声明get方法@end@implementation Score //方法的实现- (void)setCScore:(int)cScore //set方法的实现
{_cScore = cScore;_totalScore = _cScore + _ocScore;//计算总分,监听成员变量的改变_averageScore = _totalScore/2;//计算平均分
}- (int)cScore // get方法的实现
{return _cScore;
}- (void)setOcScore:(int)ocScore //set方法的实现
{_ocScore = ocScore;_totalScore = _cScore + _ocScore; //计算总分,监听成员变量的改变_averageScore = _totalScore/2;//计算平均分
}- (int)ocScore // get方法的实现
{return _ocScore;
}- (int)totalScore // get方法的实现
{return _totalScore;
}
- (int)averageScore // get方法的实现
{return _averageScore ;
}@endint main()
{Score *sc = [Score new];int t = [sc _totalScore];int a = [sc _averageScore];NSLog("总分是%d,平均分是%d",t, a);return 0;
}
4> 封装的好处
*过滤不合理的值
*屏蔽内部的赋值过程
*让外部不必关注内部细节
5类方法和对象方法对比
1> 类方法:
1、以加号+开头2、只能用类名调用,对象不能调用3、类方法中不能访问实例变量(成员变量)4、使用场合:当不需要访问成员变量的时候,尽量用类方法
2> 对象方法:
1、以减号-开头
2、只能让对象调用,没有对象,这个方法根本不可能被执行
3、对象方法能访问实例变量(成员变量)
3> 类方法和对象方法可以同名
Self:指向了方法调用者(为指向指针),代表当前对象
用self访问成员变量,区分同名的局部变量
1、使用细节
出现的地方:所有的OC方法中(对象方法\类方法),不能出现在函数
用法:
"self->成员变量名" 访问当前方法调用的成员变量"[self 方法名];" 来调用方法(对象方法\类方法)
2、常见错误
低级错误:用self去调用函数类方法中用self调用对象方法,对象方法中用self调用类方法,使self死循环