在 Objective-C 中,繼承是建立類別層級關係的核心機制。本文透過一個具體範例——從基本的 XYPoint 座標點類別,延伸出具備幾何屬性的 Circle 圓形類別——示範如何運用協定、屬性合成與方法覆寫,完成符合物件導向原則的類別設計。
首先建立一個 show 協定,規範所有幾何圖形必須實作的 printOn 方法,確保介面一致性:
@protocol show
@required
- (void)printOn;
@end
XYPoint 封裝二維座標,提供初始化方法與座標列印功能:
@interface XYPoint : NSObject {
int x;
int y;
}
@property (nonatomic, assign) int x, y;
- (id)setX:(int)_x andY:(int)_y;
@end
@implementation XYPoint
@synthesize x, y;
- (id)setX:(int)_x andY:(int)_y {
self.x = _x;
self.y = _y;
return self;
}
- (void)printOn {
NSLog(@"x = %d , y = %d", x, y);
}
@end
Circle 繼承 XYPoint,新增半徑屬性,並擴充面積、周長計算與多型列印:
@interface Circle : XYPoint {
int radius;
}
@property (nonatomic, assign) int radius;
- (id)initWithX:(int)_x andY:(int)_y andRadius:(int)_r;
- (double)area;
- (double)perimeter;
@end
@implementation Circle
@synthesize radius;
- (id)initWithX:(int)_x andY:(int)_y andRadius:(int)_r {
self.x = _x;
self.y = _y;
self.radius = _r;
return self;
}
- (double)area {
return 3.14 * radius * radius;
}
- (double)perimeter {
return 2 * 3.14 * radius; // 修正原碼中的逗號運算子錯誤
}
- (void)printOn {
NSLog(@"x = %d, y = %d, radius = %d", x, y, radius);
}
@end
show 協定統一列印介面,支援多型調用。@synthesize 自動產生存取器,簡化程式碼。Circle 重新實作 printOn,展示衍生類別專屬資訊。initWithX:andY:andRadius: 直接設定繼承而來的座標屬性,符合指定初始化器模式。原始碼第 59 行 2*3,14*radius 使用逗號運算子,導致運算邏輯錯誤;已修正為 2 * 3.14 * radius。開發時務必注意數值常數的小數點格式。