objective-c的继承给出基础例子及注意点:
- 定义并实现基类ClassA
#import <Foundation/Foundation.h> @interface ClassA : NSObject{ @public //@private @protected//objective-c有三种权限控制,同c++、java;//1、private:只被该类自己的方法使用,子类也不可用;//2、protected:默认权限,能够被子类使用;但其他类不可用;//3、public:完全开放,不建议使用; int _id; } @property int _id; -(void) setId:(int)id; -(void) printName: (NSString*) tag; @end
#import "ClassA.h" @implementation ClassA @synthesize _id; -(void) setId:(int)id{ //此处注意self调用的陷阱 //self.id = input; 造成循环调用 //[self setId:input]; 造成循环调用,与上例等价 _id = id; } -(void)printName:(NSString *)tag{ NSLog(@"%@,%i", tag,_id); } @end
- 定义并实现子类B
#import "ClassA.h" @interface ClassB : ClassA{ NSString *_name; //从编程规范性角度建议采用_XX方式 } @property NSString *_name; -(void) setId:(int)id andName:(NSString*)name; -(void) printName:(NSString *)tag; @end
#import "ClassB.h" @implementation ClassB @synthesize _name; -(void) setId:(int)id andName:(NSString *)name{ [super setId:id]; //使用super初始化基类 self._name = name; } -(void) printName:(NSString *)tag{ NSLog(@"%@,%i", [self._name stringByAppendingString:tag], self->_id); //若_id在ClassA中设置为private,则此处报错; //->不同于.操作符,.操作符相当于是用了get方法,不存在权限控制; } @end
- 测试
#import <Foundation/Foundation.h> #import "ClassA.h" #import "ClassB.h" int main(int argc, const char * argv[]) { @autoreleasepool { ClassA *tmp0 = [[ClassA alloc]init]; [tmp0 setId:21]; [tmp0 printName:@"tag"]; ClassB *tmp1 = [[ClassB alloc] init]; [tmp1 setId:3 andName:@"hi"]; [tmp1 printName:@"_fredric"]; NSLog(@"%i", tmp0->_id); //除非_id设置为public,否则报权限控制错误; } return 0; }
时间: 2024-10-12 17:11:16