zoukankan      html  css  js  c++  java
  • 继承中的自定义构造方法

    1.继承中的自定义构造方法

    • 不能在子类访问父类私有变量
    @interface Person : NSObject
    
    @property int age;
    
    - (id)initWithAge:(int)age;
    @end
    
    
    
    @interface Student : Person
    
    @property NSString *name;
    
    - (id)initWithAge:(int)age andName:(NSString *)name;
    @end
    
    @implementation Student
    
    - (id)initWithAge:(int)age andName:(NSString *)name
    {
        if (self = [super init]) {
    //        这个_Age是父类中通过property自动在.m中生成的无法继承,不能直接访问
    //        _age = age;
            [self setAge:age];
            _name = name;
        }
        return self;
    }
    @end
    • 父类的属性交给父类的方法来处理
    @interface Person : NSObject
    
    @property int age;
    
    - (id)initWithAge:(int)age;
    @end
    
    
    
    @interface Student : Person
    
    @property NSString *name;
    
    - (id)initWithAge:(int)age andName:(NSString *)name;
    @end
    
    @implementation Student
    
    - (id)initWithAge:(int)age andName:(NSString *)name
    {
        if (self = [super initWithAge:age]) {
            _name = name;
        }
        return self;
    }
    @end

    2.自定义构造方法的使用注意

    • (1)自己做自己的事情
    • (2)父类的属性交给父类的方法来处理,子类的方法处理子类自己独有的属性

    • 自定义构造方法必须以intiWith开头,并且’W’必须大写

  • 相关阅读:
    【转】千万别理程序员
    qemu-ifup and qemu-ifdown
    Fedora-23 installation in VM image
    Set up bridge to connect to internet
    fedora25 上设置br0
    助教工作总结
    树1
    线性结构
    链表基本操作
    自定义函数
  • 原文地址:https://www.cnblogs.com/xufengyuan/p/6576342.html
Copyright © 2011-2022 走看看