跟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。