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’必须大写

  • 相关阅读:
    golang并发
    golang接口
    golang方法
    golang函数
    微信小程序请求封装
    使用vue实现打印功能时出现多余空白页的问题
    mybatis 基本配置
    sql调优
    触发器 索引
    收藏 故事形式讲解javaScript中创建对象和Java创建对象的区别
  • 原文地址:https://www.cnblogs.com/xufengyuan/p/6576342.html
Copyright © 2011-2022 走看看