[Objective-C语言教程]继承(25)

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

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

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

1. 基础和派生类

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

语法如下 -

@interface derived-class: base-class

考虑一个基类Person及其派生类Employee的继承关系实现如下 -

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Person : NSObject {
 4    NSString *personName;
 5    NSInteger personAge;
 6 }
 7 
 8 - (id)initWithName:(NSString *)name andAge:(NSInteger)age;
 9 - (void)print;
10 
11 @end
12 
13 @implementation Person
14 
15 - (id)initWithName:(NSString *)name andAge:(NSInteger)age {
16    personName = name;
17    personAge = age;
18    return self;
19 }
20 
21 - (void)print {
22    NSLog(@"Name: %@", personName);
23    NSLog(@"Age: %ld", personAge);
24 }
25 
26 @end
27 
28 @interface Employee : Person {
29    NSString *employeeEducation;
30 }
31 
32 - (id)initWithName:(NSString *)name andAge:(NSInteger)age 
33   andEducation:(NSString *)education;
34 - (void)print;
35 @end
36 
37 @implementation Employee
38 
39 - (id)initWithName:(NSString *)name andAge:(NSInteger)age 
40    andEducation: (NSString *)education {
41       personName = name;
42       personAge = age;
43       employeeEducation = education;
44       return self;
45    }
46 
47 - (void)print {
48    NSLog(@"姓名: %@", personName);
49    NSLog(@"年龄: %ld", personAge);
50    NSLog(@"文化: %@", employeeEducation);
51 }
52 
53 @end
54 
55 int main(int argc, const char * argv[]) {
56    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];        
57    NSLog(@"基类Person对象");
58    Person *person = [[Person alloc]initWithName:@"Strengthen" andAge:25];
59    [person print];
60    NSLog(@"继承类Employee对象");
61    Employee *employee = [[Employee alloc]initWithName:@"Strengthen" 
62    andAge:26 andEducation:@"MBA"];
63    [employee print];        
64    [pool drain];
65    return 0;
66 }

执行上面示例代码,得到以下结果:

1 2018-11-16 01:51:21.279 main[138079] 基类Person对象
2 2018-11-16 01:51:21.280 main[138079] Name: Strengthen
3 2018-11-16 01:51:21.281 main[138079] Age: 25
4 2018-11-16 01:51:21.281 main[138079] 继承类Employee对象
5 2018-11-16 01:51:21.281 main[138079] 姓名: Strengthen
6 2018-11-16 01:51:21.281 main[138079] 年龄: 26
7 2018-11-16 01:51:21.281 main[138079] 文化: MBA

2. 访问控制和继承

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

可以通过以下方式访问它们来执行不同的访问类型。派生类继承所有基类方法和变量,但以下情况除外 -

  • 无法访问在扩展帮助下在实现文件中声明的变量。
  • 无法访问在扩展帮助下在实现文件中声明的方法。
  • 如果继承的类在基类中实现该方法,则执行继承类中的方法。
原文地址:https://www.cnblogs.com/strengthen/p/10571783.html