黑马程序员技术交流社区
标题:
OC 进阶之构造方法--->重写init方法
[打印本页]
作者:
YuePr
时间:
2015-12-10 21:19
标题:
OC 进阶之构造方法--->重写init方法
本帖最后由 YuePr 于 2015-12-10 21:32 编辑
// Person.h
// XcodePRJ01
//
// Created by YuePr on 15/12/10.
// Copyright © 2015年 CHINASof. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
@protected
NSString *_name;
}
@property NSString *name;
@property NSString *sex;
-(id)initForPerson:(NSString *)name;
@end
// Person.m
// XcodePRJ01
//
// Created by YuePr on 15/12/10.
// Copyright © 2015年 CHINASof. All rights reserved.
//
#import "Person.h"
@implementation Person
-(id)initForPerson:(NSString *)name
{
if(self = [super init])
{
_name = @"Lin Feng ";
}
return self;
}
@end
// Police.h
// XcodePRJ01
//
// Created by YuePr on 15/12/10.
// Copyright © 2015年 CHINASof. All rights reserved.
//
#import "Person.h"
@interface Police : Person
{
// @protected
NSString *_policeType;
int _policeId;
}
@property NSString *policeType;
@property int policeId;
-(void)setPoliceId:(int)policeId;
-(int)policeId;
-(void)setName:(NSString *)name;
-(NSString*)name;
-(id)initForPolicePoliceType :(NSString *)policeType andpoliceId:(int)policeid;
@end
// Police.m
// XcodePRJ01
//
// Created by YuePr on 15/12/10.
// Copyright © 2015年 CHINASof. All rights reserved.
//
#import "Police.h"
@implementation Police
-(id)initForPolicePoliceType :(NSString *)policeType andpoliceId:(int)policeid
{
if( self =[super initForPerson:@"dadaf"])
{
_policeType = policeType;
_policeId = policeid;
}
return self;
}
-(void)setName:(NSString *)name
{
_name = name;
}
-(NSString*)name
{
NSLog(@"*************");
return _name;
}
-(void)setPoliceId:(int)policeId
{
_policeId = policeId;
}
-(int)policeId
{
NSLog(@"***8282222222");
return _policeId;
}
@end
// main.m
// 多态与构造方法
//
// Created by YuePr on 15/12/10.
// Copyright © 2015年 CHINASof. All rights reserved.
//#import <Foundation/Foundation.h>
#import "Person.h"
#import "Police.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person * per1 = [[Person alloc] initForPerson:@"林峰"];
NSLog(@"%@",per1.name);
Police *policeM = [[Police alloc] initForPolicePoliceType:@"trafficPOlice" andpoliceId:1008];
NSLog(@"POLICEtype ID IS %@, ID IS %d",policeM.policeType,policeM.policeId);
NSLog(@"*****%@",policeM.name);
NSLog(@"%d",policeM.policeId);
}
return 0;
}
作者:
YuePr
时间:
2015-12-10 21:24
本帖最后由 YuePr 于 2015-12-10 21:27 编辑
注意:init方法重写的时候,(id)initForPerson 此方法自init之后的第一个单词首字母必须大写,否则编译器会当作异常错误提示。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2