OC-封装、继承和多态是面向对象编程(OOP)的三大核心特性

12 阅读3分钟

在 Objective-C 中,封装继承多态是面向对象编程(OOP)的三大核心特性。它们共同构成了代码的组织结构和设计模式,以下是详细说明:


一、封装(Encapsulation)

定义
封装是将数据(属性)和操作数据的方法(行为)绑定在一起,并对外隐藏实现细节,仅通过明确的接口与外界交互。

实现方式:

  1. 实例变量(Instance Variables)与属性(Properties)

    • 使用 @interface 声明类的成员变量(默认 @protected),但更推荐通过 @property 声明属性,自动生成 getter/setter。

    • 通过 @public@protected@private 控制访问权限:

      objectivec

      @interface Person : NSObject {
          @private
          NSString *_internalID; // 私有成员变量
      }
      @property (nonatomic, copy) NSString *name; // 公开属性
      @end
      
  2. 方法的隐藏与暴露

    • 在 .m 文件的类扩展(Class Extension)中声明私有方法和属性:

      objectivec

      @interface Person ()
      @property (nonatomic, assign) NSInteger age; // 私有属性
      - (void)privateMethod; // 私有方法
      @end
      
  3. 访问控制

    • 通过自定义的公共方法(如 - (void)updateInternalID)间接修改私有数据,避免直接操作内部状态。

示例:

objectivec

// .h 文件(公开接口)
@interface BankAccount : NSObject
@property (nonatomic, readonly) double balance; // 只读属性
- (void)deposit:(double)amount;
- (void)withdraw:(double)amount;
@end

// .m 文件(隐藏实现)
@interface BankAccount ()
@property (nonatomic, assign) double balance; // 私有可写
@end

@implementation BankAccount
- (void)withdraw:(double)amount {
    if (amount <= _balance) {
        _balance -= amount;
    }
}
@end

二、继承(Inheritance)

定义
继承允许子类复用父类的属性和方法,并扩展或重写功能,形成类之间的层次关系(单继承)。

实现方式:

  1. 语法

    objectivec

    @interface Student : Person // Student 继承自 Person
    @property (nonatomic, copy) NSString *studentID;
    @end
    
  2. 方法重写(Override)

    • 子类可以重写父类方法,通过 super 调用父类实现:

      objectivec

      @implementation Student
      - (void)introduce {
          [super introduce]; // 调用父类方法
          NSLog(@"Student ID: %@", _studentID);
      }
      @end
      
  3. 继承链

    • Objective-C 中所有类最终继承自 NSObject,它提供了基础方法(如 allocinitdescription)。

示例:

objectivec

@interface Vehicle : NSObject
- (void)startEngine;
@end

@interface Car : Vehicle // 继承自 Vehicle
- (void)drive;
@end

@implementation Car
- (void)startEngine { // 重写父类方法
    [super startEngine];
    NSLog(@"Car engine started!");
}
@end

三、多态(Polymorphism)

定义
多态允许不同类的对象对同一消息(方法调用)做出不同的响应,核心是动态绑定(运行时确定调用的具体实现)。

实现方式:

  1. 父类指针指向子类对象

    objectivec

    Animal *animal = [[Dog alloc] init]; // Animal 类型指向 Dog 对象
    [animal makeSound]; // 实际调用 Dog 的 makeSound 方法
    
  2. 方法重写(Override)

    • 子类重写父类方法,运行时根据对象实际类型调用对应实现:

      objectivec

      @interface Animal : NSObject
      - (void)makeSound;
      @end
      
      @interface Dog : Animal
      @end
      
      @implementation Dog
      - (void)makeSound {
          NSLog(@"Woof!");
      }
      @end
      
  3. 动态类型与消息机制

    • Objective-C 使用 objc_msgSend 实现动态消息派发,方法调用在运行时解析。

    • id 类型可以指向任意对象,结合 respondsToSelector: 实现灵活调用:

      objectivec

      id object = [[Dog alloc] init];
      if ([object respondsToSelector:@selector(makeSound)]) {
          [object makeSound]; // 动态调用
      }
      

示例:

objectivec

NSArray *shapes = @[[Circle new], [Square new], [Triangle new]];
for (Shape *shape in shapes) {
    [shape draw]; // 不同子类实现不同的 draw 方法
}

三者的协同作用

  • 封装 隐藏对象细节,提供安全接口。
  • 继承 实现代码复用和层次化设计。
  • 多态 基于继承,通过动态绑定提升代码灵活性和扩展性。

实际应用示例(UIKit):

objectivec

// UIView 的子类(UILabel、UIButton 等)重写 drawRect: 实现不同渲染
UIView *view1 = [[UILabel alloc] init];
UIView *view2 = [[UIButton alloc] init];
[view1 setNeedsDisplay]; // 调用 UILabel 的绘制逻辑
[view2 setNeedsDisplay]; // 调用 UIButton 的绘制逻辑

总结

  • 封装 是代码安全性的基石,通过接口隔离复杂性。
  • 继承 构建类之间的层次关系,促进代码复用。
  • 多态 利用动态绑定实现灵活的行为扩展,是 Objective-C 动态特性的核心体现。