惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
腾讯CDC
M
MIT News - Artificial intelligence
Y
Y Combinator Blog
L
LangChain Blog
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
IT之家
IT之家
A
About on SuperTechFans
H
Help Net Security

博客园 - 王彬iOS

AI时代iOS开发未来在哪里 iOS OC中多线程总结 UIVIew和CALayer的区别 iOS远程推送APNs原理和基本配置 iOS App启动过程 写个文章 iOS强制关闭暗黑模式2021.12.2 【原创】关于github那些事:如何把项目提交到coding上/gitLab上 Mac-Macs Fan Control(控制温度、随时改变风扇转速、电脑降温) Excel使用基础 NSRunLoopCommonModes和NSDefaultRunLoopMode区别(Timer) 数据统计---埋点 【问题汇总】iOS数据持久化 iOS APP 如何做才安全 【问题汇总】 【原创】苹果设备数据标准 【面试题】iOS知识大全 Swift——convenience(便利构造函数)和类方法 SVProgressHUD方法
iOS继承和多态
王彬iOS · 2024-06-25 · via 博客园 - 王彬iOS

在iOS开发中,继承(Inheritance)和多态(Polymorphism)是面向对象编程的两个核心概念。
1.继承:
继承是面向对象编程中代码复用的一种手段。在iOS中,可以通过:来继承一个类。
// 父类
@interface ParentClass : NSObject

  • (void)parentMethod;
    @end

@implementation ParentClass

  • (void)parentMethod {
    NSLog(@"Parent method called");
    }
    @end

// 子类
@interface ChildClass : ParentClass

  • (void)childMethod;
    @end

@implementation ChildClass

  • (void)childMethod {
    NSLog(@"Child method called");
    }
    @end
    在上述代码中,ChildClass继承了ParentClass,因此ChildClass拥有ParentClass的所有方法和属性。

2.多态:
多态是指一个接口多种实现,可以在运行时动态绑定实现。在iOS中,多态通常通过方法重写(Override)和方法重载(Overload)来实现。
// 父类
@interface ParentClass : NSObject

  • (void)commonMethod;
    @end

@implementation ParentClass

  • (void)commonMethod {
    NSLog(@"Parent commonMethod");
    }
    @end

// 子类
@interface ChildClass : ParentClass

  • (void)commonMethod;
    @end

@implementation ChildClass

  • (void)commonMethod {
    NSLog(@"Child commonMethod");
    }
    @end

// 使用
ParentClass *parent = [[ParentClass alloc] init];
[parent commonMethod]; // 输出:Parent commonMethod

ChildClass *child = [[ChildClass alloc] init];
[child commonMethod]; // 输出:Child commonMethod
在上述代码中,ParentClass和ChildClass都有一个名为commonMethod的方法,但是它们的实现是不同的。当我们创建ParentClass和ChildClass的实例并调用commonMethod方法时,会根据实例的实际类型调用相应的方法实现。这就是多态。
注意:在Objective-C中,多态不仅仅是方法重写,还可以通过对象的类型来判断应该调用哪个方法实现,这是动态绑定的结果。