프로그래밍/Objective C

Objective C - 상속으로 확장하기 (새 메소드 추가)

가카리 2015. 9. 14. 22:13
반응형

상속을 이해하기 위한 간단한 예제를 만들어 봅시다.

 

먼저 Rectangle클래스는 NSObject 클래스를 상속받고 Square클래스는 Rectangle클래스를 상속받습니다.

 

그리고 Rectangle클래스에서는 멤버변수들을 @property 지정을 해서 자동으로 게터와 세터 메소드를 생성시킵니다.

 

그런뒤 Square클래스에서는 self.width 를 통해 부모클래스의 width값을 접근할 수 있습니다.(게터 메소드에 의해서)

 

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 : NSObject

 

@synthesize width, height;

 

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

    width = w;

    height = h;

}

 

-(int) area{

    returnwidth*height;

}

 

-(int) perimeter{

    return (width + height) * 2;

}

 

@end

 

Square.h

#import "Rectangle.h"

 

@interface Square : Rectangle

-(void) setSide: (int) s;

-(int) side;

@end

 

Square.m

#import "Square.h"

 

@implementation Square: Rectangle

 

-(void) setSide: (int) s{

    //기존의메소드를활용함

    [selfsetWidth: s andHeight: s];

}

 

-(int) side{

    returnself.width;//게터 메소드를 활용

}

 

@end

 

main.m

#import <Foundation/Foundation.h>

#import "Rectangle.h"

#import "Square.h"

 

 

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

    @autoreleasepool {

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

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

        

        [myRect setWidth:5 andHeight: 8];

        [mySquare setSide: 5];

        

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

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

        

        

        NSLog(@"Square s = %i", [mySquare side]);//Square클래스의 side 메소드이용

        NSLog(@"Area = %i, Perimeter = %i", [mySquare area], [mySquare perimeter]);//상속받은메소드이용

        

    }

    return 0;

}

 

출력 화면

반응형