基础和派生类
Objective-C仅允许多级继承,即,它只能具有一个基类,但允许多级继承。Objective-C中的所有类均源自超类NSObject。
@interface derived-class: base-class
考虑如下基类Person及其派生类Employee-
#import <Foundation/Foundation.h>
@interface Person : NSObject {
NSString *personName;
NSInteger personAge;
}
- (id)initWithName:(NSString *)name andAge:(NSInteger)age;
- (void)print;
@end
@implementation Person
- (id)initWithName:(NSString *)name andAge:(NSInteger)age {
personName = name;
personAge = age;
return self;
}
- (void)print {
NSLog(@"Name: %@", personName);
NSLog(@"Age: %ld", personAge);
}
@end
@interface Employee : Person {
NSString *employeeEducation;
}
- (id)initWithName:(NSString *)name andAge:(NSInteger)age
andEducation:(NSString *)education;
- (void)print;
@end
@implementation Employee
- (id)initWithName:(NSString *)name andAge:(NSInteger)age
andEducation: (NSString *)education {
personName = name;
personAge = age;
employeeEducation = education;
return self;
}
- (void)print {
NSLog(@"Name: %@", personName);
NSLog(@"Age: %ld", personAge);
NSLog(@"Education: %@", employeeEducation);
}
@end
int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Base class Person Object");
Person *person = [[Person alloc]initWithName:@"Raj" andAge:5];
[person print];
NSLog(@"Inherited Class Employee Object");
Employee *employee = [[Employee alloc]initWithName:@"Raj"
andAge:5 andEducation:@"MBA"];
[employee print];
[pool drain];
return 0;
}
编译并执行上述代码后,将产生以下结果-
2020-08-20 10:17:53.583 helloWorld[7264:2884] Base class Person Object
2020-08-20 10:17:53.589 helloWorld[7264:2884] Name: Raj
2020-08-20 10:17:53.589 helloWorld[7264:2884] Age: 5
2020-08-20 10:17:53.589 helloWorld[7264:2884] Inherited Class Employee Object
2020-08-20 10:17:53.589 helloWorld[7264:2884] Name: Raj
2020-08-20 10:17:53.589 helloWorld[7264:2884] Age: 5
2020-08-20 10:17:53.589 helloWorld[7264:2884] Education: MBA