在面向對象的編程中最重要的概念之一是繼承。繼承允許我們定義一個類在另一個類,這使得它更容易創(chuàng)建和維護應用程序方面。這也提供了一個機會,重用代碼的功能和快速的執(zhí)行時間。
當創(chuàng)建一個類,而不是寫入新的數(shù)據(jù)成員和成員函數(shù),程序員可以指定新的類繼承現(xiàn)有類的成員。這種現(xiàn)有的類稱為基類,新類稱為派生類。
繼承的想法實現(xiàn)是有關系的。例如,哺乳動物是一個動物,狗是哺乳動物,因此狗是動物等。
Objective-C中允許多重繼承,也就是說,它只能有一個基類,但允許多層次的繼承。Objective-C中的所有類的超類為NSObject。
@interface derived-class: base-class
考慮一個基類 Shape 和它的派生類Rectangle 如下:
#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; }
上面的代碼編譯和執(zhí)行時,它會產(chǎn)生以下結果:
2013-09-22 21:20:09.842 Inheritance[349:303] Base class Person Object 2013-09-22上一篇:Objective-C 位運算符下一篇:Objective-C if語句