zoukankan      html  css  js  c++  java
  • Objective

    在前面, 我们学了继承的一些知识, 现在我们来学习继承的最后一个知识点, 也就是Super关键字, 在这之前, 我们就已经学过一个关键字self, 那么这次的Super又会怎么样呢? 让我们一起来看看~~~


    例子:

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    - (void)run;
    @end
    
    @implementation Person
    - (void)run
    {
        NSLog(@"跑步");
    }
    @end
    
    @interface Student : Person
    - (void)eat;
    @end
    
    @implementation Student
    - (void)eat
    {
        NSLog(@"吃东西");
    }
    @end
    
    int main()
    {
        Student *stu = [Student new];
        
        [stu eat];
        
        return 0;
    }



    我们看到, 如果我们父类有一个run的方法, 而子类没有, 如果我们要去使用父类的方法, 得花一些时间, 比如重写父类的方法, 或者用其他方法去实现, 但有了Super这个关键之后, 我们就不用这么麻烦了, 比如:

    @interface Student : Person
    - (void)eat;
    @end
    
    @implementation Student
    - (void)eat
    {
        [super run];
        NSLog(@"吃东西");
    }
    @end



    Super在这里就是去父类寻找是否有该方法, 如果有就会调用, 如果没有就会继续往上找, 直到找不到报错为止.



    Super的作用

    1.直接调用父类中的某个方法

    2.Super处在对象方法中,那么就会调用父类的对象方法

       Super处在类方法中,那么就会调用父类的类方法

     

    3.使用场合: 子类重写父类的方法时想保留父类的一些行为




    好了, 这次我们就讲到这里, 下次我们继续~~

  • 相关阅读:
    day06 字典、元组、set的方法及常用操作
    python makestrans translate
    python 中locals() 和 globals()
    threading.local()
    进程 线程 协程
    微信机器人
    flask
    python is ==
    Beautiful Soup 4.4.0 基本使用方法
    12306
  • 原文地址:https://www.cnblogs.com/iOSCain/p/4282846.html
Copyright © 2011-2022 走看看