Object C繼承及實例變量的作用域

[main.m]

#import foundation/Foundation.h>

#import "Student.h"

//面向對象語言的特點:封裝 ?繼承 多態

//繼承:也叫派生,子類繼承父類,在交類的繼承派生自己的實例變理及方法

//peson 類 student類:peson類是student的父類。student類是pdeson類的子類

//superClass父類的訪問,subClass子類的訪問

//parentClass父親的訪問,childClass 子類的訪問

//OC的寫法

//@interface Student:person ?//student 類繼承于person類

//@end

//子類繼承父類,子類繼承父類非私有的實例變量及非私有的方法

//子類實例變更構成=父類實例變量+子類自定義的實例變量

//子類方法構成=父類非私有方法+子類自定義的方法


int main(int argc,const char *argv[]){

@autorelesepool{

Student *stu=[[Student alloc]] init];

//繼承父類的方法

stu.name=@"小飛";

stu.age=12;

//子類自定義的方法

stu.num=45;

stu.score=99;

[stu printStudent];

打印結果:name=小飛 age=12

? ? ? ? ? ? ? ? ? ?num=45 ?score=99

}

//受保護的

//stu->_weight=45.7//不可以直接訪問受保護的實例變量

//通過setter,getter方法訪問受保護的實例變量

stu.weight=56.7;

NSLog(@"weight=%.2f",stu.weight);

打印結果:weight=56.7

//私有的

//stu->_height=100;//不可以直接訪問私有的實例變量

sut.height=178;

NSLog(@"height=%.2f",stu.height);//類外需通過setter,getter方法間接訪問

打印結果:height=178

//公共的

sut->_place=@"北京";

NSLog(@"place=%@",stu->_palce)

打印結果:pace=北京

}

return 0;

}


//創建一個person類

【person.h】

#import <foundation/Foundation.h>

@interface Person:NSObject

{

NSString *_name;

NSInteger _age;

//實例變量作用域

@protected //(缺省)受保護的實例變量,在當關類內可以直接訪問,子類可以直接繼承,在類外不可以直接訪問,可以通過方法(setter,getter方法)的調用間接訪問

float _weight;

@private //私有的實例變量,在當前類內可以直接訪問,子類不能繼承,子類可以通過方法間接訪問,在類外不能直接訪問。

float _height;

@public //公共的實例變量,在當前類內可以直接訪問,子類可以直接繼承,類外也可以直接訪問,通過->(指針運算符)直接訪問

NSString *_palce;

}

@property(nonatomic,assign)float weight;

@Property(nonatomic,assign)folat height;

@property (nonatomic,copy)NSString *name;

@property(nonatomic,assign)NSInteger age;

//默認展開的實例變理是私有變量,若放更改為受保護的在{}中定義即可

@proerty(nonatomic,copy)NSString *fristName;

@end


【person.m】

#import "person.h"

@implementation Person

//setter方法

-(void)setHeight:(float)height

{

_height = height;

}

//getter方法

-(float)height

{

return _height;

}

@end


【創建Student類,繼承 Peson類】

【Student.h】

#import "person.h"

@interface Student:person

{

NSInteger _num ;//學號

NSInteger _score;//分數

}

@property (nonatmic,assign)NSInteger num;

@property (nonatmic,assign)NSInteger score;

//缺省的

-(void)print Student;

//受保護的

-(void)changeWeight;

//私有的

-(void)changeHeight;

//公共的

-(void)changPlace;

//未定義在實例變量{}中使用的property關鍵字

-(void)chantFirstName;

@end


【Student.m】

#import "Student.h"

@implementation Student

-(void)printStudent

{

//訪問從父類繼承的實例變量

NSLog(@"name=%@" age=%li,_name,_age);

//訪問自定義的實例變量

NSLog(@num=%li score=%li",_num,_score);

}

//受保護的

-(void)changeWeight{

_weight=56.7;

}

//私有的

-(void)changeHeight{

{

//_height=45;//子類不能繼承父類的私有實例變量

self.height=176;//通過調用setter方法,間接訪問私有實例變量;

}

//公共的

-(void)chantPlace

{

_palce=@"上海";

}

//未定義實例變量,使用的是property關鍵字;

-(void)chantFirstName{

//_firstName=@"小飛"; 無法調用,因property關鍵字是將實例變量展開到.m文件

}

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容