码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-10-06 01:02:29      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:io   ar   文件   sp   c   on   cti   log   r   

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

标签:io   ar   文件   sp   c   on   cti   log   r   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!