黑马程序员——封装

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

1.set方法:
 1>提供一个方法给外界设置成员变量值,可以在方法里对变量进行过滤。
 2>命名规范:
  * 方法名以set开头
  * set后跟上成员变量名,变量首字母大写
  * 返回值为void
  * 一定要接收一个参数,参数类型跟成员变量类型一致
  * 形参名不能跟成员变量名一样

2.get方法:
 1>返回对象内部的成员变量。
 2>命名规范:
  * 方法名跟成员变量名一样
  * 肯定有返回值,类型肯定跟成员变量类型一致
  * 不需接收任何参数


3.设计一个Student类

#inport<Foundation/Foundation.h>
//声明
@interface Student :NSObject
{
 int _age;
}

-(void)seAge:(int)newAge;
-(int)age;
-(void)study;
@end

@implementation JiSuanQi


//方法的实现
-(void)seAge:(int)newAge
{
 if(newAge<=0)
   {
  newAge = 1;
   }
 _age = newAge;
}

-(int)age
{
 return _age; 
}

-(void)study
{
 NSLog(@"%d岁",age); 
}
@end

int main()
{
 Student *s = [Student new];
 [s setAge:0];访问        
 [s study];
 NSLog(@"这是%d岁",[s age]);
}


输出结果:1岁
   这是1岁

总结:
    1.封装:不让成员变量暴露,不能轻易改变量值,所以不再用@public
   将变量的设置封装进一个set方法中,保证数据安全性。
   所以,用set方法设置成员变量的值,用get方法访问成员变量
    2.假如有成员变量 int no;只允许外界访问,不允许外界修改,这种情况下只需
      提供get方法;若只允许修改不允许外界访问,只提供set方法。
 
    3.变量名命名规范:要以下划线_开头

 好处:
         * 成员变量名与get方法名区分开
  * 可跟局部变名区分开
  

4.设计一个成绩类
    *C语言成绩(可读可写)  
    *OC成绩(可读可写)
    *总分(只读)
    *平均分(只读)

#inport<Foundation/Foundation.h>
//声明
@interface Score :NSObject
{
 int _ocScore;
 int _cScore;
 int _totalScore;
 int _averageScore;
}

-(void)setCScore:(int)cScore;
-(int)cScore;

-(void)setOCScore:(int)ocScore;
-(int)ocScore;

-(int)totalScore;
-(int)averageScore;
@end

@implementation Score

//方法的实现
-(void)setCScore:(int)cScore
{
 _cScore = cScore;
}
-(int)cScore
{
 return _cScore;
}

-(void)setOCScore:(int)ocScore
{
 _ocScore = ocScore;
}
-(int)ocScore
{
 return _ocScore;
}

//法一:不设int _totalScore和int _averageScore两个成员变量
//并把它们的get方法设为:
-(int)totalScore
{
 return _cScore + _ocScore;
}
-(int)averageScore
{
 return (_cScore + _ocScore)/2;
}

//法二:像声明中那样,依旧设置4个变量,set且把前两个变量的
//set方法和后两个变量的get方法设置为:
-(void)setCScore:(int)cScore
{
 _cScore = cScore;
 _totalScore = _cScore + _ocScore;
 _avrageScore = _totalScore/2;
}

-(void)setOCScore:(int)ocScore
{
 _ocScore = ocScore;
 _totalScore = _cScore + _ocScore;
 _avrageScore = _totalScore/2;
}

-(int)totalScore
{
 return _totalScore;
}

-(int)averageScore
{
 return _avrageScore ;
}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值