MyRectangle.h
//========================================== #import <Foundation/Foundation.h> @interface MyRectangel:NSObject{ int width; int height; } -(MyRectangel*) initWithWidth:(int) weight andHeight:(int) height; -(void) setWidth:(int) width; -(void) setHeight:(int) height; -(int)width; -(int)height; -(void) area; @end //=============================================== #import "MyRectangle.h" -(MyRectangel*) initWithWidth:(int) weight andHeight:(int) height{ self = [supert 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{ NSLog(@"%d",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; } @endmain.m
//=============================================== @import "MySquare.h" int main(argc,const char * argv[]){ MyRectangel *r = [[MyRectangle alloc] initWithWidth:2 andHeight:5]; [r area]; MySquare *s = [[MySquare alloc] initWithSize:6]; [s area];//调用父类的方法,计算面积 [r release]; [s release]; }