直接来代码然后给出个人理解
FKFruit.h文件
#import <Foundation/Foundation.h>
@interface FKFruit : NSObject
{
int _a; // 会被继承
}
@property (nonatomic, assign) int a;
@end
FKFruit.m文件
#import "FKFruit.h"
@interface FKFruit () {
int b; // 不会被继承
}
@end
@implementation FKFruit
- (instancetype)init {
self = [super init];
if (self) {
_a = 12;
}
return self;
}
@end
FKApple.h文件 继承 FKFruit
#import "FKFruit.h"
@interface FKApple : FKFruit
- (void)test;
@end
FKApple.m文件
#import "FKApple.h"
@interface FKApple () {
int _a;
}
@end
@implementation FKApple
- (void)test {
NSLog(@"%d", _a); // 默认访问的子类的成员变量
NSLog(@"%d", super.a); // 只有在父类提供了getter方法时,才能使用 注释掉父类的 @property (nonatomic, assign) int a; ,此处就会报错
}
@end
调用test方法的运行结果:
2016-05-18 08:20:07.036 Demo1[583:8920] 0
2016-05-18 08:20:07.038 Demo1[583:8920] 12
Program ended with exit code: 0
/*
总结:
1.头文件中声明的变量和方法都会被继承
2.在子类的头文件中不能定义和父类相同的变量
3.在子父类存在同名的方法时,子类中使用super关键字访问父类的方法
4.在字符类存在同名的变量时,子类中使用super关键字访问父类的变量,且父类变量一定要提供getter和setter方法
*/