OC中封裝與多態的實例

/*
 設計一個成績類
 屬性:C語言成績 OC成績 IOS成績
 行爲:    比較C語言成績,返回自己與其他成績差
        比較OC成績、比較IOS成績、計算總分、計算平均分
 */

#import <Foundation/Foundation.h>

@interface YObject : NSObject
-(void)printClassName;

@end

@implementation YObject

-(void)printClassName{

    NSLog(@"%@",[self class]);
}

@end


//定義成績類
@interface ChengJi : YObject
{
    //屬性
    
    //c語言成績
    int _cScore ;
    
    //oc成績
    int _ocSocre ;
    
    //ios成績
    int _iosScore;
    
}
@property int cScore;
@property int ocScore;
@property int iosScore;
//比較C語言成績
-(int) comparisonCWith:(ChengJi*)chengJi;
//比較OC語言成績
-(int) comparisonOcWith:(ChengJi*)chengJi;
//比較IOS成績
-(int) comparisonIosWith:(ChengJi*)chengJi;

//計算總分
-(int)getSumScore;
//計算平均分
-(int)getAverageScore;



@end


@implementation ChengJi

@synthesize cScore = _cScore;
@synthesize ocScore = _ocSocre;
@synthesize iosScore = _iosScore;

-(int) comparisonCWith:(ChengJi*)chengJi{
    return self.cScore - chengJi.cScore;
}
-(int) comparisonOcWith:(ChengJi*)chengJi{
    return self.ocScore - chengJi.ocScore;
}
-(int) comparisonIosWith:(ChengJi*)chengJi{
    return self.iosScore - chengJi.iosScore;
}
//計算總分
-(int)getSumScore{
    return self.cScore+self.ocScore+self.iosScore;
}
//計算平均分
-(int)getAverageScore{
    return [self getSumScore]/3;
}


@end



int main(){
    
    ChengJi *chengJi1 = [ChengJi new];
    chengJi1.cScore = 100;
    chengJi1.ocScore = 100;
    chengJi1.iosScore = 100;

    ChengJi *chengJi2 = [ChengJi new];
    chengJi2.cScore = 90;
    chengJi2.ocScore = 80;
    chengJi2.iosScore = 70;
    
    [chengJi1 printClassName];

    NSLog(@"第一個比第二個的C語言成績高%d分",[chengJi1 comparisonCWith: chengJi2]);
//    [ChengJi printClassName];
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章