类的继承是oop中的基本原则,下面就来分析一下oc的类和继承
在实现继承出现了子类的.m文件报错 mission@end 导致程序没发编译,最后发现是.h中少了一个@end
父类 TestExtends.h文件
@interface TestExtends: NSObject{
NSString* name;
}
@property NSString *name; //类似set和get方法
//@property name;
-(void)setName:(NSString*)newName;//定义方法
-(id)initWithC:(NSString*)newName;//定义构造方法
@end
#endif /* TestExtends_h */
TestExtends.m文件
#import <Foundation/Foundation.h>
#import "TestExtends.h"
@implementation TestExtends
@synthesize name;
-(void)setName:(NSString*)newName{
NSLog(@"调用父类的setName方法");
}
-(id)initWithC:(NSString *)newName{
if (self==[super init]) {
name=newName;//
NSLog(@"父类的构造方法被调用。。。。");
}
return self;
}
@end
mian文件
TestExtends* te=[[TestExtends alloc] init];
[te setName:@"Object-c"];
NSLog(@"简单的实现");
运行结果:
2015-11-04 22:35:10.327 test_01[1287:67105] 调用父类的setName方法
2015-11-04 22:35:10.328 test_01[1287:67105] 简单的实现
(lldb)
分析
创建对象
TestExtends* te=[[TestExtends alloc] init];
调用setName方法
[te setName:@"Object-c"];
NSLog(@"简单的实现");
子类 定义Person类继承TestExtends类
TestExtends.h文件
#import "TestExtends.h" @interface Person :TestExtends @property NSString* address;//定义变量 -(void)setAddress:(NSString*)newAssress;//定义方法 -(id)initWithChild:(NSString*)newAssress;//定义构造函数的方法 @end #endif /* Person_h */
TestExtends.m文件
#import "Person.h"
@implementation Person
@synthesize address;
-(void)setAddress:(NSString *)newAssress{
[super setName:newAssress];
NSLog(@"子类的地址是%@",newAssress);
}
-(id)initWithChild:(NSString *)newAssress{
if (self==[super initWithC:newAssress]) {
address=newAssress;
NSLog(@"子类的构造函数被调用了。。。");
}
return self;
}
@end
main文件
Person* tec=[[Person alloc]initWithChild:@"Android"];
[tec setAddress:@"China"];
运行结果:
2015-11-04 22:40:42.288 test_01[1306:70521] 父类的构造方法被调用。。。。 2015-11-04 22:40:42.289 test_01[1306:70521] 子类的构造函数被调用了。。。 2015-11-04 22:40:42.289 test_01[1306:70521] 调用父类的setName方法 2015-11-04 22:40:42.289 test_01[1306:70521] 子类的地址是China (lldb)
分析:
1, Person* tec=[[Person alloc]initWithChild:@"Android"];创建对象首先调用父类的方法:原因如下
-(id)initWithChild:(NSString *)newAssress{
if (self==[super initWithC:newAssress]) {//调用父类的构造方法
address=newAssress;
NSLog(@"子类的构造函数被调用了。。。");
}
return self;
}
2, [tec setAddress:@"China"];方法中存在 [supersetName:newAssress];调用父类的方法
将mian文件中的 Person* tec=[[Personalloc]initWithChild:@"Android"];
[tec setAddress:@"China"];
改为 TestExtends* te=[[Person alloc] init];
[te setName:@"nihao"];
运行结果:
2015-11-04 23:20:16.150 test_01[1479:87156] 调用父类的setName方法
5964

被折叠的 条评论
为什么被折叠?



