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

OOP思想:封装、继承、多态

时间:2014-10-06 00:46:29      阅读:336      评论:0      收藏:0      [点我收藏+]

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

1. 构建一个动物类作为父类,猫科动物子类继承动物类,老虎子类继承猫科 动物 每个类都实现一个不同的cry方法。

借口文件1:Animal.h

#import <Foundation/Foundation.h>

@interface Animal : NSObject
- (void) cry;

@end

实现文件1:Animal.m

#import "Animal.h"

@implementation Animal
- (void) cry
{
    NSLog(@"%@",@"The animal is crying!");
}

@end

 

借口文件2:Feline.h

#import "Animal.h"

@interface Feline : Animal
- (void) cry;

@end

实现文件2:Feline.m

#import "Feline.h"

@implementation Feline
- (void) cry
{
    NSLog(@"%@",@"The feline is crying!");
}


@end

 

借口文件3:Tiger.h

#import "Feline.h"

@interface Tiger : Feline
- (void) cry;

@end


实现文件3:Tiger.m

#import "Tiger.h"

@implementation Tiger
- (void) cry
{
    NSLog(@"%@",@"The tiger is crying!");
}

@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]));
    }
}


 

2. 构建Transportation、Car、Lorry类,分别定义run方法。

借口文件1:Transportation.h

#import <Foundation/Foundation.h>

@interface Transportation : NSObject
- (void) run;

@end

 

实现文件1:Transportation.m

#import "Transportation.h"

@implementation Transportation
- (void) run
{
    NSLog(@"%@",@"The transportation is runing!");
}


@end

 

借口文件2:Car.h

#import "Transportation.h"

@interface Car : Transportation
- (void) run;


@end


实现文件2:Car.m

#import "Car.h"

@implementation Car
- (void) run
{
    NSLog(@"%@",@"The car is runing!");
}


@end

 

借口文件3:Lorry.h

#import "Car.h"

@interface Lorry : Car
- (void) run;


@end


实现文件3:Lorry.

#import "Lorry.h"

@implementation Lorry
- (void) run
{
    NSLog(@"%@",@"The lorry is runing!");
}

@end


测试文件:main.m

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Lorry.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        Transportation *transportation = [[Transportation alloc]init];
        Car *car = [[Car alloc]init];
        Lorry *lorry = [[Lorry alloc]init];
        
        [transportation run];
        [car run];
        [lorry run];
        
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}


OOP思想:封装、继承、多态

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

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

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