Contents ...
udn網路城邦
繼承
2011/02/20 21:08
瀏覽371
迴響0
推薦0
引用0
這是Programming in Objective-C 2.0第八章的內容,用來介紹物件導向的繼承(inheritance)。
長方型類別(Rectangle class)裡面定義了二個整數instance variables,且定了setter and getter methods來對這二個instance variables進行存取的工作,另外定義了算週長,面積等methods。
正方型是長方型的一種,它的定義和長方型一樣,但是它的長、寛相等。如正方型類(Square class)繼承長方型類,則長方型類所有的methods,正方型的物件都可以使用。下面是例子:
Rectangle.h:

#import <Foundation/Foundation.h>


@interface Rectangle : NSObject {


 int width;


 int height;


}


@property int width, height;


-(void) setWidth: (int) w andHeight: (int) h;


-(int) area;


-(int) perimeter;


-(Rectangle *) initWithWidth: (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 2*width+2*height;


}


-(Rectangle *) initWithWidth: (int) w andHeight: (int) h{


 self = [super init];


 if (self)


 [self setWidth:w andHeight:h];


 return self;


}


@end


Square.h:

#import "Rectangle.h"


@interface Square : Rectangle 


-(void) setSide:(int)s;


-(int) side;

-(Square *)initWithSide: (int) s;

 

@end

Square.m:

#import "Square.h"


@implementation Square


-(void) setSide: (int) s{


 [self setWidth:s andHeight:s];


}


-(int) side{


 return width;


}


-(Square *)initWithSide: (int) s{


 self=[super init];


 if (self)


 [self setSide:s];


 return self;


}

 

@end

主程式:

#import <Foundation/Foundation.h>


#import "Square.h"


int main (int argc, const char * argv[]) {


 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


 Rectangle *myRect = [[Rectangle alloc] initWithWidth:5 andHeight:8];


 Square *mySquare = [[Square alloc] initWithSide:5];


 


 NSLog(@"長方型w=%i,h=%i", myRect.width, myRect.height);


 NSLog(@"長方型面積Area = %i, 週長Perimeter = %i",[myRect area],[myRect perimeter]);




 NSLog(@"正方型邊長s=%i", [mySquare side]);


 NSLog(@"正方型面積Area = %i, 週長Perimeter = %i",[mySquare area],[mySquare perimeter]);




 [myRect release];


    [pool drain];


    return 0;


}

編譯執行結果:

長方型w=5,h=8


長方型面積Area = 40, 週長Perimeter = 26


正方型邊長s=5


正方型面積Area = 25, 週長Perimeter = 20









全站分類:知識學習 其他
自訂分類:Objective-C
上一則: Objective-C的category
下一則: More On Class and Methods

限會員,要發表迴響,請先登入