若用繼承擴充原本既有的程式碼,
可相對節省不少時間在重新打造輪子上,
本範例先創造一個矩形Rectangle class,
在創造一個Square class並繼承於Rectangle,
並重複利用area, perimeter這兩個method
最後用main.m黨印出並驗證,程式碼如下,
Rectangle.h
#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
@property int width, height;
-(int) area;
-(int) perimeter;
-(void) setWidth: (int) w andHeight: (int) h;
@end
Rectangle.m
#import "Rectangle.h"
@implementation Rectangle
@synthesize width, height;
-(void) setWidth: (int) w andHeight: (int) h
{
width = w;
height = h;
}
-(int) area
{
return width * height;
}
-(int) perimeter
{
return (width + height) * 2;
}
@end
Square.h
#import "Rectangle.h" @interface Square : Rectangle //
繼承於Rectangle-(void) setSide: (int) s; -(int) side; @end
Square.m
#import "Square.h"
@implementation Square
-(void) setSide: (int) s
{
[self setWidth: s andHeight: s];
}
-(int) side
{
return self.width;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "Square.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Rectangle * rectangle = [[Rectangle alloc]init];
[rectangle setWidth:6 andHeight:10];
NSLog(@"rectangle: w = %i, h = %i", rectangle.width, rectangle.height);
NSLog(@"Area = %i, Perimeter = %i", [rectangle area], [rectangle perimeter]);
Square * square = [[Square alloc]init];
[square setSide: 8];
NSLog(@"square: s = %i,", square.side);
NSLog(@"Area = %i, Perimeter = %i", [rectangle area], [rectangle perimeter]);
//透過繼承, 由此可見不用在Square.m重新實作area與perimeter這兩個method
}
return 0;
}
文章標籤
全站熱搜
留言列表