zoukankan      html  css  js  c++  java
  • Objective-C 封装 继承 多态

    封装

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject {
        //@public
        int _age;
    }
    - (void) setAge : (int) age;
    - (int) age;
    @end
    
    @implementation Person
    - (void) setAge : (int) age {
        if(age <= 0) {
            age = 1;
        }
        _age = age;
    }
    - (int) age {
        return _age;
    }
    @end
    
    int main() {
        Person *p = [Person new];
        //p->age = 10;
        //NSLog(@"年龄是: %i", p->age);
        
        [p setAge : 0];
        NSLog(@"年龄是: %i", [p age]);
        return 0;
    }
    
    /** 注意我的命名规范 **/
    //封装的好处: 代码的安全性高

    继承和组合

    #import <Foundation/Foundation.h>
    
    @interface AClass : NSObject {
        int _age;
        int _height;
    }
    @end
    
    @implementation AClass
    @end
    
    /** 继承 **/
    @interface BClass : AClass{
    }
    @end
    
    @implementation BClass
    @end
    
    /** 组合 **/
    @interface CClass : NSObject {
        AClass *_aClass;
    }
    @end
    
    @implementation CClass
    @end
    
    int main() {
        return 0;
    }
    
    //注意: OC是单继承
    //子类方法和属性的访问过程: 如果子类没有 就去访问父类的 //子类和父类不能有相同的成员变量 //子类和父类可以有相同的方法(方法的重写) /** 继承的好处 **/ //不改变原来模型的基础上 拓充方法 //建立类与类之间的联系 //抽取了公共代码 /** 继承的坏处 **/ //耦合性强 /** super 关键字 **/ //直接调用父类中的方法 [super 方法名] //super 处在对象方法中就会调用父类的对象方法 //super 处在类方法中就会调用父类的类方法 //使用场合: 子类重写父类的方法时想保留父类的一些行为

    多态

    #import <Foundation/Foundation.h>
    
    @interface Animal : NSObject
    - (void) eat;
    @end
    
    @implementation Animal
    - (void) eat {
        NSLog(@"Animal在吃东西");
    }
    @end
    
    @interface Dog : Animal
    @end
    
    @implementation Dog
    - (void) eat {
        NSLog(@"Dog在吃东西");
    }
    @end
    
    int main() {
        Animal *a = [Dog new];
        [a eat];
        return 0;
    }
    
    /** 多态 **/
    //多态只存在子父类继承关系中
    //子类对象赋值给父类指针
    
    /** 多态的好处 **/
    //用父类接收参数 节省代码
    
    /** 多态的局限性 **/
    //父类类型的变量不能直接调用子类特有的方法(可以考虑强制转换)
    
    /** 多态的细节 **/
    //动态绑定: 在运行时根据对象的类型确定动态调用的方法 
  • 相关阅读:
    js原型链
    js的__proto__,prototype、constructor属性
    百度ife2015-小白的弯路2
    百度ife2015-小白的弯路1
    Visaul Studio 密钥
    pycharm常用的一些快捷键
    python3练习题--字符串
    字符串相关方法
    python3 基本数据类型
    在python中缩进的重要性
  • 原文地址:https://www.cnblogs.com/huangyi-427/p/4597666.html
Copyright © 2011-2022 走看看