面试题答案
一键面试方法重写基本语法规则
- 方法签名:在子类中重写父类方法时,方法的名称、参数列表和返回值类型必须与父类中被重写的方法完全一致。
- 访问修饰符:在Objective - C中,访问修饰符(
@public
、@protected
、@private
)对于方法重写没有限制,子类重写的方法访问权限可以与父类相同或者更宽松,但不能更严格。例如,父类方法是@protected
,子类重写后可以是@protected
或者@public
,但不能是@private
。
示例
#import <Foundation/Foundation.h>
// 父类
@interface Animal : NSObject
- (void)makeSound;
@end
@implementation Animal
- (void)makeSound {
NSLog(@"Animal makes a sound.");
}
@end
// 子类
@interface Dog : Animal
- (void)makeSound;
@end
@implementation Dog
- (void)makeSound {
NSLog(@"Dog barks.");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Animal *animal = [[Animal alloc] init];
[animal makeSound];
Dog *dog = [[Dog alloc] init];
[dog makeSound];
}
return 0;
}
在上述代码中,Dog
类继承自Animal
类,并对makeSound
方法进行了重写。Animal
类的makeSound
方法输出“Animal makes a sound.”,而Dog
类重写后的makeSound
方法输出“Dog barks.”。