iOS中類似java抽象類理解。
阿新 • • 發佈:2019-02-05
/** * @author 麥子, 15-09-26 12:09:57 * * 抽象類IOS這邊無法規定子類必須實現一個方法,這邊只是一個警號,編譯依然能過。所以感覺無法控制編寫程式碼的規範。 具體的就是。 通過父類實現對應的協議, 其中必須實現的也就是java中的抽象方法。 而可選實現的方法,也就是java中的實現的方法。 */ int main(int argc, const char * argv[]) { @autoreleasepool { Animal *cat = [[Cat alloc] init]; [cat animalType:@"貓"]; NSLog(@"-------------------"); Animal *dog = [[Dog alloc] init]; [dog animalType:@"狗"]; } return 0; }
#import <Foundation/Foundation.h>
@protocol AnimalProtocol <NSObject>
- (void)eat;
- (void)play;
@optional
- (void)animalType:(NSString *)animalName;
@end
#import "Animal.h" @implementation Animal - (void)animalType:(NSString *)animalName{ [self eat]; [self play]; NSLog(@"這是一隻%@",animalName); } @end
#import "Cat.h"
@implementation Cat
- (void)eat{
NSLog(@"喜歡吃魚");
}
- (void)play{
NSLog(@"玩耗子");
}
@end
#import "Dog.h"
@implementation Dog
- (void)eat{
NSLog(@"喜歡吃骨頭");
}
- (void)play{
NSLog(@"喜歡玩球");
}
@end
列印結果如下:
2015-09-26 13:05:40.031 設計模式_ios抽象類理解[2861:454758] 喜歡吃魚
2015-09-26 13:05:40.032
2015-09-26 13:05:40.032 設計模式_ios抽象類理解[2861:454758] 這是一隻貓
2015-09-26 13:05:40.032 設計模式_ios抽象類理解[2861:454758] -------------------
2015-09-26 13:05:40.033 設計模式_ios抽象類理解[2861:454758] 喜歡吃骨頭
2015-09-26 13:05:40.033 設計模式_ios抽象類理解[2861:454758] 喜歡玩球
2015-09-26 13:05:40.033 設計模式_ios抽象類理解[2861:454758] 這是一隻狗