标签:
set方法:
get方法:
1 #import <Foundation/Foundation.h> 2 3 @interface Person : NSObject 4 { 5 int _age; //年龄 6 double _weight; // 体重 7 } 8 9 //年龄的setter和getter声明 10 - (void)setAge:(int)age; 11 - (int)age; 12 13 @end 14 15 @implementation Person 16 17 //年龄的setter和getter实现 18 - (void)setAge:(int)age{ 19 if (age <= 0) { 20 _age = 1; 21 }else{ 22 _age = age; 23 } 24 } 25 26 - (int)age{ 27 return _age; 28 } 29 30 @end 31 32 //测试age的setter和getter 33 int main(){ 34 Person *p = [Person new]; 35 [p setAge:-3]; 36 NSLog(@"年龄为%d", [p age]); 37 return 0; 38 }
1 #import <Foundation/Foundation.h> 2 /************Person类************/ 3 @interface Person : NSObject 4 { 5 int _age; //年龄 6 double _weight; // 体重 7 } 8 9 //年龄的setter和getter声明 10 - (void)setAge:(int)age; 11 - (int)age; 12 13 @end 14 15 @implementation Person 16 17 //年龄的setter和getter实现 18 - (void)setAge:(int)age{ 19 if (age <= 0) { 20 _age = 1; 21 }else{ 22 _age = age; 23 } 24 } 25 26 - (int)age{ 27 return _age; 28 } 29 30 @end 31 32 /**************Studengt类***************/ 33 @interface Studengt : Person 34 35 @end 36 37 @implementation Studengt 38 39 @end 40 41 //测试Student类 42 int main(){ 43 Studengt *stu = [Studengt new]; 44 [stu setAge:17]; 45 NSLog(@"学生的年龄是%d", [stu age]); 46 47 return 0; 48 }
因为Studengt类继承了Person类,所以虽然子类没有明确说明实例变量和方法,但是学生依然有年龄_age的实例变量以及_age的getter和setter
但是继承有很多需要注意的地方:
duplicate member
标签:
原文地址:http://www.cnblogs.com/oucding/p/4418375.html