object-c之继承

跟Java一样,只支持单继承,多继承需要用portocol。

#import <Foundation/Foundation.h> 
@interface MyRectangle: NSObject{ 
    int width; 
    int height; 
} 
-(MyRectangle*) initWithWidth: (int) weight andHeight: (int) height; 
-(void) setWidth: (int) width; 
-(void) setHeight: (int) height; 
-(int) width; 
-(int) height; 
-(void) area;//计算面积
@end 

#import "MyRectangle.h" 
@implementation MyRectangle 
-(MyRectangle*) initWithWidth: (int) w andHeight: (int) h{ 
    self=[super init]; 
    if(self){ 
        [self setWidth: w]; 
        [self setHeight: h]; 
    } 
} 
-(void) setWidth: (int) w{ 
    width=w; 
} 
-(void) setHeight: (int) h{ 
    height=h; 
} 
-(int) width{ 
    return width; 
} 
-(int) height{  
return height; 
} 
-(void) area{ 
    printf("%d\n",width*height); 
} 
@end 

#import "MyRectangle.h"

@interface MySquare:MyRectangle{
int size;
}
-(MySquare*)initWithSize:(int)size;
-(void)setSize:(int)size;
-(int)size;
@end

#import "MySquare.h"

@implementation MySquare
-(MySquare*)initWithSize:(int)s{
self=[super init];
if(self){
[self setWidth:s];
[self setHeight:s];
}
return self;
}

-(void) setSize:(int)s{
size=s;
}

-(int)size{
return size;
}
@end

#import "MySquare.h"

int main(int argc,const char *argv[]){
MyRectangle *rec=[[MySquare alloc]initWithSize:10];
[rec area];
[rec release];
return 0;
}

好了,经常make后无问题。

然后继续测试isMemberOfClass

#import "MySquare.h"

int main(int argc,const char *argv[]){
MyRectangle *rec=[[MySquare alloc]initWithSize:10];

if([rec isMemberOfClass:[MyRectangle class]]){
NSLog(@"rec isMemberofClass of MyRectangle.\n");
}
else{
NSLog(@"rec is not MemberofClass of MyRectangle.\n");
}

if([rec isMemberOfClass:[MySquare class]]){
NSLog(@"rec isMemberofClass of MySquare.\n");
}
else{
NSLog(@"rec is not MemberofClass of MySquare.\n");
}

[rec release];
return 0;
}

从结果看出,编译器不认为

rec
是MyRectangle而是MySquare。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值