[Obj-C] 03 Objective-C 2.0学習 “継承とクラス”

[Mac M2 Pro 12CPU, Ventura 13.6, clang 15.0.0]
教本:『詳解 Objective-C 2.0 第3版』(2011年) chap.3

Objective-Cのクラス継承について学びました。

下記のコードでは[y method2]のところで循環するのではないかと思いましたが、superを呼び出した時点でスーパークラスはclass Aに固定されるようです。

今さらですが、@interfaceはヘッダファイル、@implementationはソースファイルに分割可能でしたね。Objective-Cアプリは昨年6月に初めて書いたきりなので、すっかり忘れていました。

#import <Foundation/NSObject.h>
#import <stdio.h>

@interface A: NSObject
- (void)method1;
- (void)method2;
@end

@implementation A
- (void)method1 { printf("method1 of Class A\n"); }
- (void)method2 { printf("method2 of Class A\n"); }
@end

@interface B: A
- (void)method2;
@end

@implementation B
- (void)method2 {
    printf("method2 of Class B\n");
    printf("self --> ");
    [self method1];
    printf("super--> ");
    [super method2];
}
@end

@interface C: B
- (void)method1;
@end

@implementation C
- (void)method1 { printf("method1 of Class C\n"); }
@end

int main(void)
{
    id x = [[B alloc] init];
    id y = [[C alloc] init];
    printf("--- instance of B ---\n");
    [x method1];
    [x method2];
    printf("--- instance of C ---\n");
    [y method1];
    [y method2];
    return 0;
}
--- instance of B ---
method1 of Class A
method2 of Class B
self --> method1 of Class A
super--> method2 of Class A
--- instance of C ---
method1 of Class C
method2 of Class B
self --> method1 of Class C
super--> method2 of Class A // 循環にならない