首页 > 其他 > 详细

OOP思想:封装、继承、多态(续)

时间:2014-10-05 23:04:29      阅读:354      评论:0      收藏:0      [点我收藏+]

借口文件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思想:封装、继承、多态(续)

原文:http://www.cnblogs.com/jiuchabaikaishui/p/4007467.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!