多态

时间:2014-01-16 08:59:11   收藏:0   阅读:396

继承

1.在Oc中每个类对象最开始的位置都会有一个isa指针,该指针指向一块内存区域,分发表中先找本类,再找父类方法.

 2. self在实例方法中表示当前对象指针,在类方法中表示该类指针。


1.多态:建立在继承之上,同一类型对象对同一方法呈现不同的实现(方法)状态。(常用情况)

2.多态的实现方法:

3.通过定义一个通用的调用方法,以简化调用(好处符合单一责任原则):

如:在虚函数中定义-(void)show;-(void)showContext;

  实现-(void)show{},-(void)showContext{[self show]};

4.id动态数据类型


Animal.h

bubuko.com,布布扣
@interface Animal : NSObject
{
    NSString *_name;
}
@property(nonatomic,retain)NSString *name;

-(Animal *)initWithName:(NSString *)aName;

/*
声明虚函数(方法)
*/
-(void)learn;

/*
统计学习的内容
*/
-(void)statisInfo;
@end
bubuko.com,布布扣

Animal.m

bubuko.com,布布扣
#import "Animal.h"

@implementation Animal
@synthesize name = _name;

-(Animal *)initWithName:(NSString *)aName
{
    self = [super init];
    if (self)
    {
        self.name = aName;
    }
    return self;
}
/*
虚函数:什么都不用实现
 */
-(void)learn
{
    
}

//统计学习内容
-(void)statisInfo
{
   //NSLog(@"第%d个",++i);
    [self learn];
}
@end
bubuko.com,布布扣

Preson.h

#import "Animal.h"

@interface Person : Animal

@end

Preson.m

bubuko.com,布布扣
#import "Person.h"
@implementation Person

-(void)learn
{
   
    NSLog(@"学习吃东西");
}
@end
bubuko.com,布布扣

Student.h

#import "Person.h"

@interface Student : Person

@end

Student.m

bubuko.com,布布扣
#import "Student.h"


@implementation Student
-(void)learn
{
    [super learn];
    NSLog(@"学习ios开发技能");
}

@end
bubuko.com,布布扣

AppDelegate.m

bubuko.com,布布扣
#import "AppDelegate.h"
#import "Animal.h"
#import "Person.h"
#import "Student.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    Animal *s = [[Student alloc]initWithName:@"jobs"];
    [s statisInfo];

    [self.window makeKeyAndVisible];
    return YES;
}
bubuko.com,布布扣

原文:http://www.cnblogs.com/huen/p/3517914.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!