您的位置:首页 > 移动开发 > Objective-C

黑马程序员---object-c知识点总结(一)封装,继承,多态

2014-08-20 21:58 483 查看
-----------android培训java培训、java学习型技术博客、期待与您交流!------------ 

#import<Foundation/Foundation.h>

//动物颜色的枚举值

typedef enum {

    ColorRed ,

    ColorBlack ,

    ColorGreen,

    ColorWrite

} Color ;

//动物性别的枚举值

typedef enum {

    SexBoy,

    SexGirle,

    SexUnknown

} Sex ;

//声明Animal类的属性

@interface Animal : NSObject

{

    Color _color ;

    Sex _sex ;

    int _age ;

}

//设置动物的颜色

- (void)setColor:(Color)color ;

//获得动物的颜色

- (Color)color ;

//设置动物的性别

- (void)setSex:(Sex)sex ;

//获得动物的性别

- (Sex)sex ;

//设置动物的年龄

- (void)setAge:(int)age ;

//获得动物年龄

- (int)age ;

//动物跑的行为

- (void)run ;

//动物吃的行为

- (void)feed ;

@end

//实现Animal的功能

@implementation Animal

- (void)setColor:(Color)color

{

    _color = color ;

}

- (Color)color

{

    return _color ;

}

- (void)setSex:(Sex)sex

{

    _sex = sex ;

}

- (Sex)sex

{

    return _sex ;

}

- (void)setAge:(int)age

{

    _age = age ;

}

- (int)age

{

    return _age ;

}

- (void)run

{

    NSLog(@"动物,-----跑起来了");

}

- (void)feed

{

    NSLog(@"动物,-----吃饱了");

}

@end

@interface Dog : Animal

- (void)run ;

- (void)feed ;

+ (void)run ;

+ (void)feed ;

@end

@implementation Dog

- (void)run

{

    NSLog(@"狗狗,-----跑起来了");

}

- (void)feed

{

    NSLog(@"狗狗,-----吃饱了");

}

+ (void)run

{

    NSLog(@"狗,++++++跑起来了");

}

+ (void)feed

{

    NSLog(@"狗,++++++吃饱了");

}

@end

int main()

{

    Animal * animal = [Animal new] ;

    [animal run] ;

    //Animal * a1 = [Dog new];

    //[Dog run];可以这样转换但是有缺陷,不建议使用

    

    //使用强制转化法
父类指针转化为子类对象

    Animal * a1 = [Dog new];

    Dog * p1 = (Dog *)a1

    [p1 run];

    [Dog run];

    [a1 run] ;

    return 0 ;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: