본문 바로가기

C/Objective C/Objective C

Objective C 상속 예제 따라하기 두번째

- 도형에 관한 상속 예제이다.

- 소스코드

#import <Foundation/Foundation.h>


@interface Rectangle : NSObject{

int width;

int height;

}

@property int width, height;

-(int)area;

-(int)perimeter;

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


@end 

#import "Rectangle.h"


@implementation Rectangle

@synthesize width, height;

-(int)area{

return width*height;

}

-(int)perimeter{

return (width+height)*2;

}

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

width = w;

height = h;

}

@end 

이제 정사각형을 다뤄 보자. Square라는 클래스를 새로 정의하고 Rectangle 클래스에서 했던 것처럼 유 사한 메서드를 정의하는 방식도 있다. 혹은, 정사각형이 직사각형에서 너비와 높이가 똑같은 특별한 도형 임을 인식해서 해결해도 된다. 

#import <Foundation/Foundation.h>

#import "Rectangle.h"


@interface Square : Rectangle

-(void) setSide: (int)s;

-(int) side;


@end 

#import "Square.h"


@implementation Square

-(void) setSide: (int)s{

[self setWidth:s andHeight:s];

}

-(int) side{

return width;

}

@end 

#import <Foundation/Foundation.h>

#import "Rectangle.h"

#import "Square.h"


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

{

Rectangle *myRect = [[Rectangle alloc]init];

[myRect setWidth:5 andHeight:8];

NSLog(@"Rectangle : w = %i, h = %i", myRect.width, myRect.height);

NSLog(@"Area = %i, Perimeter = %i",[myRect area], [myRect perimeter]);

    return 0;

Square *mySquare = [[Square alloc]init];

[mySquare setSide:5];

NSLog(@"Square : s = %i", [mySquare side]);

NSLog(@"Area = %i, Perimeter = %i",[mySquare area], [mySquare perimeter]);

return 0;

} 


- 실행화면