@interface 區塊描述了 class 中所包含的元件 (components) 以及相關的方法 (methods).
@implementation 區塊包含了執行方法 (methods) 的實際代碼.
program 區塊包含了最終此程式要達成目的原始代碼.
用下面的一段程式碼來實作上面的說明:
//Source start
#import <Foundation/Foundation.h>
//@interface 區塊開始
@interface CarFactory: NSObject
{
int carWheels;
int carPassengers;
}
-(void) report;
-(void) setWheels: (int) n;
-(void) setPassengers: (int) n;
@end
//@implementation 區塊開始
@implementation CarFactory
-(void) report
{
NSLog(@"The final product is a car with %i wheels and %i passengers for maximum.", carWheels, carPassengers);
}
-(void) setWheels: (int) n
{
carWheels = n;
}
-(void) setPassengers: (int) n
{
carPassengers = n;
}
@end
//program 區塊開始
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
CarFactory *newCAR; //宣告 newCAR 是一個為 CarFactory 類型的 object
newCAR = [CarFactory alloc]; //為 newCAR 保留一塊記憶體空間, 相當於生產一輛新車
newCAR = [newCAR init]; //初始化 newCAR 這個 instance
[newCAR setWheels: 6]; //指定該車擁有 6 個輪胎
[newCAR setPassengers: 20]; //指定該車最大載客人數為 20 人
[newCAR report];
[newCAR release]; //釋放 newCAR 佔用的記憶體空間
[pool drain];
return 0;
}
//Source end
最後得到的輸出結果就是:
The final product is a car with 6 wheels and 20 passengers for maximum.