Objective C의 다형성은 다른 클래스들 간에 동일한 메서드 이름을 사용할 수 있는 기능입니다.
이러한 다형성 을 이용해 각 클래스 정의에서 특정한 매세드에 필요한 코드를 뽑아내서 다른 클래스의 정의로부터 독립적으로 만드는 방식이 가능합니다.
또한 다형성을 통해 동일한 이름의 메서드에 응답할 수 있는 새로운 클래스를 추가할 수도 있습니다.
실습을 해봅시다. Complex와 Fraction 클래스를 생성합니다.
Complex.h
#import <foundation/foundation.h>
@interface Complex : NSObject {
double real;
double imaginary;
}
@property double real, imaginary;
-(void) print;
-(void) setReal: (double) a andImaginary: (double) b;
-(Complex *) add: (Complex *) f;
//자기자신의 콤플랙스에 콤플렉스로 만들어진 객체(복소수)를 넘겨준다.
@end
Complex.m
#import "Complex.h"
@implementation Complex
@synthesize real, imaginary;
-(void) print
{
NSLog (@" %g + %gi ", real, imaginary);
}
-(void) setReal: (double) a andImaginary: (double) b
{
real = a;
//실수에 a
imaginary = b;
//허수에 b
}
-(Complex *) add: (Complex *) f
{
Complex *result = [[Complex alloc] init];
[result setReal: real + [f real] andImaginary: imaginary + [f imaginary]];
return result;
}
@end
Fraction.h
#import <Foundation/Foundation.h>
@interface Fraction : NSObject {
int numerator;
int denominator;
}
@property int numerator, denominator;
-(void) print;
-(void) setTo: (int) n over: (int) d;
-(double) convertToNum;
-(void) reduce;
//두개를 더하고 나서 공통약수를 나누어준다.
-(Fraction *) add: (Fraction *) f;
@end
Fraction.m
#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print
{
NSLog (@"%i/%i", numerator, denominator);
}
-(double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return 1.0;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c) / (b * d)
// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;
resultNum = numerator * f.denominator + denominator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
}
@end
Main.m
#import "Fraction.h"
#import "Complex.h"
int main (int argc, char * argv[]) {
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 = [[Fraction alloc] init];
Fraction *fracResult;
Complex *c1 = [[Complex alloc] init];
Complex *c2 = [[Complex alloc] init];
Complex *compResult;
[f1 setTo: 1 over: 10];
[f2 setTo: 2 over: 15];
[c1 setReal: 18.0 andImaginary: 2.5];
[c2 setReal: -5.0 andImaginary: 3.2];
// add and print 2 complex numbers
[c1 print];
NSLog (@" ---------");
compResult = [c1 add: c2];
[compResult print];
NSLog (@"\n");
// add and print 2 fractions
[f1 print]; NSLog (@" +"); [f2 print];
NSLog(@"----");
fracResult = [f1 add: f2];
[fracResult print];
return 0;
}
Command + R 을 눌러 결과를 살펴봅시다.
5-2 동적 바인딩과 id형