zoukankan      html  css  js  c++  java
  • 黑马程序员--构造方法重写和desception方法重写

    ------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

    构造方法的作用及用法



    我们新建一个学生类,但是学生的学号是自动生成的,所以声明icast这个成员变量中我们加了一个readonly,不允许外部设置他的属性


    内容包含了构造方法的重写和description的重写,重写的方法的方式和目的



    // 学生的声明文件

    #import <Foundation/Foundation.h>



    @interface Student : NSObject

    @property (nonatomic,strong) NSString *name;

    @property (nonatomic,strong,readonly) NSString *icast; // 只读

    @property (nonatomic,assign) int age;

    @end


    // 学生的实现文件

    #import "Student.h"


    @implementation Student

    - (Student *)init

    {

        if(self =[super init])

        {

            static unsigned long icast = 1101080600;

            icast++; // 自动给学号加1

            // 初始化同时分配学号

      _icast = [NSString stringWithFormat:@"%lu",icast];


        }

    /*

    若把这两句写在if外,会出现有的学号没有对应的学生

    static unsigned long icast = 1101080600;

        icast++;


    */

        return self;

    }


    // 重写description

    - (NSString *)description

    {

        return [NSString stringWithFormat:@"name : %@, age : %i , icast : %@",_name, _age, _icast];

    }

    @end


    // test文件

    #import <Foundation/Foundation.h>

    #import "Student.h"


    int main(int argc, const char * argv[]) {

        @autoreleasepool {

            Student *stu = [[Student alloc] init];

            stu.name = @"Jack";

            stu.age = 20;

            NSLog(@"%@",stu);

            

            Student *stu1 = [[Student alloc] init];

            NSLog(@"%@",stu1);

            

        }

        return 0;

    }

     








    构造方法:用来初始化对象的方法,是个对象方法,-开头

        1.重写构造方法的目的:为了让对象创建出来,成员变量就会有一些固定的值

        2.重写构造方法的注意点

    1>.先调用父类的构造方法([super init]

    2>.再进行子类内部成员变量的初始化

        3.完整地创建一个可用的对象

    1>.分配存储空间  +alloc


    调用+alloc分配存储空间

    Student *stu1 = [Student alloc];

    2>.初始化 -init

    调用-init进行初始化

    Student *st2 = [Student init];




    这种写法会导致死循环

    - (NSString *)description

    {

        return [NSString stringWithFormat:@“%@“,self];

    }


  • 相关阅读:
    Redis学习——(1)Redis安装与配置
    Ubuntu14.04安装Apache2+SVN+Trac
    Ubuntu14.04配置文件Apache2.conf
    Ubuntu系统用户忘记密码
    java中无符号类型的处理[转]
    Golang 切片(slice)扩容机制源码剖析
    无线网络:无线城域网和无线广域网
    vue项目 镜像重置的命令
    批量下载阿里云rpm包
    HttpClient psot和get请求
  • 原文地址:https://www.cnblogs.com/frozen1224/p/4244838.html
Copyright © 2011-2022 走看看