試試看寫一支物件導向的簡單程式吧。題目是:輸出學生的數學跟科學的成績。

在這之前,我們可以先用一般的C來寫寫看,如下:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[])

{

    @autoreleasepool

    {

        int scoreMath = 83;

        int scoreScience = 75;

        NSLog (@"The score of math is %i, science is %i", scoreMath, scoreScience);

    }

    return 0;

}

這是一個很簡單的C語言程式,輸出數學跟科學的分數分別為83分及75分。然而若我們要輸出很多學生的分數時,我們勢必要處理一大堆一樣的動作,很煩人對吧。這時我們可以定義一個"StudentScore"的實體,來收集數學及科學的分數;換句話說,我們可以從定義一個類別開始做起。

#import <Foundation/Foundation.h>

//---- Interface section ----

@interface StudentScore:NSObject

-(void) print;

-(void) setScoreMath:(int) m;

-(void) setScoreScience:(int) s;

@end

 

//---- Implementation section ----

@implementation StudentScore

{

    int scoreMath;

    int scoreScience;

}

-(void)print

{

    NSLog(@"math score is %i, science score is %i", scoreMath, scoreScience);

}

-(void)setScoreMath: (int) m

{

    scoreMath = m;

}

-(void)setScoreScience: (int) s

{

    scoreScience = s;

}

@end

 

//---- Program section ----

int main(int argc, char *argv[])

{

    @autoreleasepool

    {

        StudentScore *aStudent;

        aStudent = [Student alloc];

        aStudent = [aStudent init];

 

        [aStudent setScoreMath: 83];

        [aStudent setScoreScience: 75];

        NSLog (@"This student's ");

        [aStudent print];

    }

    return 0;

}

從上述例子來看,我們可以分成三個部分:

@interface section

@implementation section

program setcion

我們會在interface section 裡描述類別及方法,反之在implementation section描述資料及在interface裡所定義的方法所需要的,真正的code。Program就是去實現這些類別。

arrow
arrow
    全站熱搜

    Eason 發表在 痞客邦 留言(0) 人氣()