——Java培訓、Android培訓、iOS培訓、.Net培訓、期待與您交流! ——-
類的封裝
/*
在oc語言中使用@interface和@implementation來處理類
類的封裝
變量默認只能被當前類的對象方法訪問。*/
//不封裝的缺點:
//當一個類把自己的屬性暴露在外部的時候,那麼該類就會失去對屬性的管理權。
/*
get方法的實現規範
get的方法一定是一個對象方法
get 方法一定有返回值,返回值類型和實例變量的類型一致
get 方法名,是去掉換線的實例變量名
get方法 一定沒有參數
get 方法的實現一定是返回實例變量值,
以後獲取name的值,都同意的使用name的get方法
-(NSString *)name
-(int)age;
//(int)_age;
-(sex)sex;
//-(sex)_sex;
*/
#import <Foundation/Foundation.h>
@interface Gun :NSObject // 對象的聲明
{
int _bulletcount ;
}
-(void)shoot ;
-(void)setBulletCount;
@end
@implementation Gun //對象的實現
-(void)shoot{
if (_bulletcount > 0){ //調用函數的封裝
_bulletcount--;
NSLog(@"tutu...剩餘子彈:%d",_bulletcount );
}else{
NSLog(@"沒有子彈");
}
}
-(void)setBulletCount :(int)bulletCont{
if (bulletCont>0){
_bulletcount=bulletCont; //函數的封裝
}else {
_bulletcount=0;
}
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Gun *gun =[Gun new];
// gun ->_bulletcount = 3;
[gun setBulletCount:3];
[gun shoot ];
[gun shoot ];
[gun shoot ];
[gun shoot ];
}
return 0;
}
類的繼承
繼承的注意事項
自類不能定義和父類同名的變量,但同時可以繼承父類的變量.
@interface dog:animal
{
int _tuiNum ;
}
oc 繼承體系中的方法調用順序
1、在自己類中找
2、如果如果沒有去父類中找
3、如果父類麼有,還往上找,直到找到爲止,直到基類
4、如果基類(NSObject)中沒有就會報錯
類多態的概念和條件
多態的條件
多態的條件:有繼承關係,有方法重寫