IOS征途之二 OC實現繼承

今天是正式下定決定學好IOS的第二天,用代碼寫了一個繼承的勵志。因爲對比以往經驗來說,繼承直接影響了代碼的美觀性,可讀性。
(再順便mark一個疑問,IOS似乎並不重視抽象類的使用?網上有人說協議protocol可代替,可是還未領略到其中之美,mark有待觀察)

OC繼承實例代碼如下:

目錄結構:
這裏寫圖片描述

基類:

BaseAnimal.h

#import <Foundation/Foundation.h>

@interface BaseAnimal : NSObject
-(void)eat;
-(void)runSpeed : (int) speed;
@end

BaseAnimal.m

#import "BaseAnimal.h"

@implementation BaseAnimal
-(void)eat
{
    NSLog(@"Nothing!");
}
-(void) runSpeed : (int) speed
{
    NSLog(@"runSpeed is %i" , speed);
}
@end

Dog.h

#import <Foundation/Foundation.h>
#import "BaseAnimal.h"

@interface Dog : BaseAnimal{

}
@end

Dog.m

#import "Dog.h"

@implementation Dog
- (void)eat
{
    NSLog(@"Dog eat shit!");
}
@end

Cat.h
略.

Cat.m

#import "Cat.h"

@implementation Cat

@end

main.m

#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Cat.h"

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

    @autoreleasepool {

        Dog *d = [[Dog alloc] init];
        [d eat];
        [d runSpeed:5];

        Cat *c = [[Cat alloc] init];
        [c eat];
        [c runSpeed:2];

    }
    return 0;
}

運行結果:

2015-09-14 23:54:46.412 Lesson2[888:303] Dog eat shit!
2015-09-14 23:54:46.414 Lesson2[888:303] runSpeed is 5
2015-09-14 23:54:46.415 Lesson2[888:303] Nothing!
2015-09-14 23:54:46.415 Lesson2[888:303] runSpeed is 2
Program ended with exit code: 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章