首页 > 代码库 > OOP思想:封装、继承、多态(续)
OOP思想:封装、继承、多态(续)
借口文件1:Bird.h
#import <Foundation/Foundation.h>
@interface Bird : NSObject
{
@private
int _weight;
NSString *_name;
}
- (void)fly;
@end
实现文件1:Bird.m
#import "Bird.h"
@implementation Bird
- (void)fly
{
NSLog(@"%@",@"Bird is flying!");
}
@end
借口文件2:Sparrow.h
#import "Bird.h"
@interface Sparrow : Bird
{
//@protected
//@public
//@private
NSString *_ID;
}
@property(nonatomic,assign)NSString* ID;
- (void)set_ID:(NSString *)id;
- (void)print_ID;
- (void)sing;
@end
实现文件2:Sparrow.m
#import "Sparrow.h"
@implementation Sparrow
- (void)set_ID:(NSString *)id
{
_ID=id;
}
- (void)print_ID
{
NSLog(@"%@",_ID);
}
- (void)sing
{
NSLog(@"%@",@"Sparrow is singing!");
}
@end
借口文件3:BlackSparrow.h
#import "Sparrow.h"
@interface BlackSparrow : Sparrow
- (void)eat;
- (void)sing;
@end
实现文件3:BlackSparrow.m
#import "BlackSparrow.h"
@implementation BlackSparrow
- (void)fly
{
NSLog(@"%s",__PRETTY_FUNCTION__);
}
- (void)eat
{
NSLog(@"%s",__PRETTY_FUNCTION__);
}
- (void)sing
{
NSLog(@"%s",__PRETTY_FUNCTION__);
}
@end
测试文件:main.m
int main(int argc, char * argv[]) {
@autoreleasepool {
Bird *bird=[[Bird alloc]init];
[bird fly];
Sparrow *sparrow=[[Sparrow alloc]init];
[sparrow fly];
[sparrow sing];
[sparrow set_ID:@"1234"];
[sparrow print_ID];
Bird *bird1=[[BlackSparrow alloc]init];
BlackSparrow *bs = bird1;//强制类型转换
bs.ID = @"sssss";
[bird1 fly];
[bird1 eat];
[bird1 sing];
[bird1 print_ID];
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
OOP思想:封装、继承、多态(续)