これを見てください:
#import <Foundation/Foundation.h>
@interface A : NSObject { }
- (A*) newItem;
- (void) hello;
@end
@interface B : A { int filler; }
- (B*) newItem;
- (void) hello;
- (void) foo;
@end
@implementation A
- (A*) newItem { NSLog(@"A newItem"); return self; }
- (void) hello { NSLog(@"hello from A"); }
@end
@implementation B
- (B*) newItem { NSLog(@"B newItem"); return self; }
- (void) hello { NSLog(@"hello from B: %d", filler); }
- (void) foo { NSLog(@"foo!"); }
@end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
A *origA = [A new];
A *myA = [origA newItem];
NSLog(@"myA: %@", myA);
B *origB = [B new];
B *myB = [origB newItem];
A *myBA = [origB newItem];
NSLog(@"myB: %@\nmyBA: %@", myB, myBA);
[origA hello];
[origB hello];
[myA hello];
[myB hello];
[myBA hello];
NSLog(@"Covariance?");
[pool drain];
return 0;
}
これはかなり圧縮された構文であり、メモリ管理はうまくいきませんが、それnewItem
が仮想的 ( に送信newItem
するとa がmyBA
返されるB
) であり、共変であることがわかります。
次のこともできることに注意してください。
B *myAB = (B*)[origA newItem];
しかし、それはを返し、A
それに送信foo
すると、クラスがセレクターに応答しないことがわかり#foo
ます。キャストを省略した場合(B*)
、コンパイル時にこれに関する警告が表示されます。
しかし、Objective-C では、ISTM の共分散は大きな問題ではありません。