oc中的构造方法和description方法

oc和其他面向对象语言一样,也支持构造方法,当我们初始化一个对象的时候传入这个构造方法需要的值,而oc中的description方法相当于Java中的tostring方法都来自于父类。

#import <Foundation/Foundation.h>

@interface Person :NSObject{

    int _age; 

   int _no;

}

- (int)age;

-(void)setAge:(int)age;


-(int)no;

-(void)setNo:(int)no;

//声明一个构造方法

-(id)initWithAge:(int)age andNo:(int)no;//返回idid代表任何对象

@end


#import "Person.h"


@implementation Person


-(int)age{

   return_age;

}

-(int)no{ 

   return_no;

}


-(void)setAge:(int)age{

   _age=age;

}

-(void)setNo:(int)no{

   _no=no;

}

-(id)initWithAge:(int)age andNo:(int)no{

    //先调用父类的构造方法

    //self=[super init];

    if(self=[superinit]){//如果这里不判断,有可能会产生空对象,实际上是self!=niu

       // _age=age;

       // _no=no;

       self.age=age;

       self.no=no;

        

    }

    return self;

}

//重写父类的description方法

-(NSString *)description{

    NSString *str=[NSStringstringWithFormat:@"age=%i and no=%i",_age,_no];

   return str;

}

@end


int main(int argc,constchar * argv[])

{


    @autoreleasepool {

       Person *p=[[Person alloc]init];

       //Person *p=[Person new]; oc中也有new关键字,alloc一个对象并init

        

  [p initWithAge:25andNo:110];//利用构造方法初始化一个对象

        NSLog(@"对象的地址是%@",p);//调用了description方法

       //释放对象

        [prelease];

        

    }

   return0;

}

self与动态方法、静态方法的关系

//在动态方法中self代表了调用方法的对象

-(void)selfMethod{

   int age=self.age;

}

//在静态方法中表示调用方法的当前类

+(void)selfMethod2{

    [selfalloc];//[Person alloc];

}

成员变量的作用域(默认是@protected)

@publicNSString *name; //全局都可以访问

@privateNSString *tel; //只能在类内部访问

@protectedNSString *address;//只能在类内部和子类中访问

总结:
1.因为在objectc中没有包,所以也不像java中一样存在包权限。

2.如果在.h文件中没有声明方法,而只在.m文件中实现,那么这个方法就是私有方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值