美文网首页OC
OC中父类与子类之间相互调用

OC中父类与子类之间相互调用

作者: 飞天猪Pony | 来源:发表于2018-06-29 15:36 被阅读26次

定义一个父类FatherViewController 和一个子类SonViewController,其中子类继承父类。

@interface SonViewController : FatherViewController
父类与子类中都声明一个外部方法doSomething,如下:

子类:

@interface SonViewController : FatherViewController
-(void) doSomething;
@end

方法实现:

-(void) doSomething
{
    NSLog(@"this is son funtion....");
}

父类:

@interface FatherViewController : UIViewController
-(void) doSomething;
@end

方法实现:

-(void) doSomething
{
    NSLog(@"this is father function....");
}

1、正常的实例化调用场景:

我们在另一个类中分别实例化它们,并调用如下:

SonViewController *sVC1 = [[SonViewController alloc]init];
[sVC1 doSomething];
FatherViewController *fVC2 = [[FatherViewController alloc]init];
[fVC2 doSomething];

打印的结果如下:
2018-04-22 20:50:54.775 Banksy[10645:203402] this is son funtion....
2018-04-22 20:50:54.775 Banksy[10645:203402] this is father function....

2、子类中调用自己的方法以及父类的方法场景:

实例化子类,并在子类的init方法中,调用自己和父类的方法,如下:

-(instancetype)init
{
    self = [super init];
    
    [self doSomething]; //如果子类中没有doSomething方法的实现,那么这时就会调用父类的
    [super doSomething];
    
    return self;
}

打印结果如下:
2018-04-22 20:53:57.617 Banksy[10700:205200] this is son funtion....
2018-04-22 20:53:57.617 Banksy[10700:205200] this is father function....

3、父类调用子类的方法的场景:

此时若实例化了子类,而在父类中的init方法中会调用的doSomething方法,父类调用方式如下:

- (instancetype)init
{
    self = [super init];
    
    [self doSomething];
    
    return self;
}

打印结果如下:
2018-04-22 20:57:17.329 Banksy[10754:206797] this is son funtion....

此时的[self doSomething],调用的是子类的方法,因为此时的self为SonViewController,

相关文章

  • OC中父类与子类之间相互调用

    定义一个父类FatherViewController 和一个子类SonViewController,其中子类继承父...

  • Objective-c 子类继承父类私有方法

    笔记: 在OC中 如果子类重写了父类的私有方法,父类不会再调用本类的实现,而是直接调用子类的实现。切记,切记。

  • OC 中子类如何调用父类的私有方法

    OC中能实现子类调用父类的私有方法吗? 调用父类的私有方法无非是想做两种操作:1.父类的实现完全不适用于子类(需完...

  • python 面向对象: super()

    python 关于 super 的使用 子类对象调用父类方法 :super(B,b).hh() 子类中调用父类方法...

  • iOS 小知识点总结

    子类实现父类方法时,监测子类是否调用super方法。 在父类中声明方法时: 子类中实现该父类方法: 图片压缩

  • OC 在子类中调用父类方法

    需求 在控制器A中实现了webview的一些协议方法,控制器Aa继承了控制器A,并且也需要重写一些webview的...

  • 继承

    子类与父类有同名方法,是为覆盖,调用子类实例时,执行子类中方法,如果需要调用父类则需要super关键字

  • Python3中的MRO C3算法

    我们知道python中的类与类之间是可以相互继承的。在继承关系中,子类自动拥有父类中除了私有属性之外的其他所有内容...

  • python继承二(实例)

    父类 子类一 采用父类名.方法的方式调用父类中的初始化函数" 子类二 " 使用super(子类名,self).方法...

  • java基础问题

    在多态中,父类指向子类时候,不能调用父类没用,子类有的方法。 java中普通类可以继承普通类的。

网友评论

    本文标题:OC中父类与子类之间相互调用

    本文链接:https://www.haomeiwen.com/subject/kbyayftx.html