父类MyRectangle.h
#import <Foundation/Foundation.h>
@interface MyRectangle : NSObject
{
int width;
int height;
}
-(MyRectangle*)initWithWidth:(int)w height:(int)h;
-(void)setWidth:(int)w;
-(void)setHeight:(int)h;
-(void)setWidth:(int)w height:(int)h;
-(int)width;
-(int)height;
-(void)print;
@end
MyRectangle.m
#import "MyRectangle.h"
@implementation MyRectangle
-(MyRectangle*)initWithWidth:(int)w height:(int)h{
self=[super init];
if(self){
[self setWidth:w height:h];
}
return self;
}
-(void)setWidth:(int)w{
width=w;
}
-(void)setHeight:(int)h{
height=h;
}
-(void)setWidth:(int)w height:(int)h{
width=w;
height=h;
}
-(int)width{
return width;
}
-(int)height{
return height;
}
-(void)print{
printf("width=%i height=%i\n",width,height);
}
@end
#import "MyRectangle.h"
@interface Square : MyRectangle
-(Square*)initWithSize:(int)s;
-(void)setSize:(int)s;
-(int)size;
@end
Square.m
#import "Square.h"
@implementation Square
-(Square*)initWithSize:(int)s{
self=[super init];
if(self){
[self setSize:s];
}
return self;
}
-(void)setSize:(int)s{
width=s;
height=s;
}
-(int)size{
return width;
}
//重写父类方法
-(void)setWidth:(int)w{
printf("Square重写MyRectangle中setWidth方法\n");
[self setSize:w];
}
-(void)setHeight:(int)h{
printf("Square重写MyRectangle中setHeight方法\n");
[self setSize:h];
}
@end
main.m
#import "MyRectangle.h"
#import "Square.h"
#import <stdio.h>
int main(int argc, const char * argv[])
{
MyRectangle *rec=[[MyRectangle alloc]initWithWidth:10 height:20];
Square *sq=[[Square alloc]initWithSize:15];
printf("MyRectangle:");
[rec print];
printf("Square:\n");
[sq print];
//更新sq
[sq setSize:18];
printf("重写的Square\n");
[sq print];
//调用父类
[sq setWidth:30];
int d=[sq width];
printf("调用父类且自己未重写的方法%i\n",d);
//释放内存
[rec release];
[sq release];
}
运行结果