Objective-C 继承(Inheritance)

面向对象编程中最重要的概念之一是继承。继承允许我们根据另一个类定义一个类,它使得创建和维护应用程序更加容易,也提供了重用代码功能和快速实现的机会。

创建类时,程序员可以指定新类继承现有类的成员,而不是编写全新的数据成员和成员函数。这个现有类称为 基类,新类称为 派生类

继承的思想 实现了一种 关系。例如,哺乳动物是动物,狗是哺乳动物,因此狗也是动物等等。


基类与派生类

Objective-C 只支持多级继承,即它只能有一个基类,但允许多级继承。Objective-C 中的所有类都派生自超类 NSObject

  1. @interface derived-class: base-class

参考下面的一个基类 Person 和它的派生类 Employee:

  1. #import <Foundation/Foundation.h>
  2. @interface Person : NSObject {
  3. NSString *personName;
  4. NSInteger personAge;
  5. }
  6. - (id)initWithName:(NSString *)name andAge:(NSInteger)age;
  7. - (void)print;
  8. @end
  9. @implementation Person
  10. - (id)initWithName:(NSString *)name andAge:(NSInteger)age {
  11. personName = name;
  12. personAge = age;
  13. return self;
  14. }
  15. - (void)print {
  16. NSLog(@"Name: %@", personName);
  17. NSLog(@"Age: %ld", personAge);
  18. }
  19. @end
  20. @interface Employee : Person {
  21. NSString *employeeEducation;
  22. }
  23. - (id)initWithName:(NSString *)name andAge:(NSInteger)age
  24. andEducation:(NSString *)education;
  25. - (void)print;
  26. @end
  27. @implementation Employee
  28. - (id)initWithName:(NSString *)name andAge:(NSInteger)age
  29. andEducation: (NSString *)education {
  30. personName = name;
  31. personAge = age;
  32. employeeEducation = education;
  33. return self;
  34. }
  35. - (void)print {
  36. NSLog(@"Name: %@", personName);
  37. NSLog(@"Age: %ld", personAge);
  38. NSLog(@"Education: %@", employeeEducation);
  39. }
  40. @end
  41. int main(int argc, const char * argv[]) {
  42. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  43. NSLog(@"Base class Person Object");
  44. Person *person = [[Person alloc]initWithName:@"Raj" andAge:5];
  45. [person print];
  46. NSLog(@"Inherited Class Employee Object");
  47. Employee *employee = [[Employee alloc]initWithName:@"Raj"
  48. andAge:5 andEducation:@"MBA"];
  49. [employee print];
  50. [pool drain];
  51. return 0;
  52. }

结果如下:

  1. 2022-07-07 21:20:09.842 Inheritance[349:303] Base class Person Object
  2. 2022-07-07 21:20:09.844 Inheritance[349:303] Name: Raj
  3. 2022-07-07 21:20:09.844 Inheritance[349:303] Age: 5
  4. 2022-07-07 21:20:09.845 Inheritance[349:303] Inherited Class Employee Object
  5. 2022-07-07 21:20:09.845 Inheritance[349:303] Name: Raj
  6. 2022-07-07 21:20:09.846 Inheritance[349:303] Age: 5
  7. 2022-07-07 21:20:09.846 Inheritance[349:303] Education: MBA

访问控制和继承

如果派生类在接口类中定义,则派生类可以访问其基类的所有私有成员,但不能访问实现文件中定义的私有成员。

我们可以根据谁可以通过以下方式访问它们来总结不同的访问类型:

派生类继承所有基类方法和变量,但有以下例外:

  • 无法访问在扩展名帮助下在实现文件中声明的变量。
  • 无法访问在扩展名帮助下在实现文件中声明的方法。
  • 如果继承的类在基类中实现了方法,则执行派生类中的方法。