IOS Objective-C 继承(虚方法)

来源:互联网 发布:网络约车运营许可证 编辑:程序博客网 时间:2024/05/11 05:01
#import <Foundation/Foundation.h>@interface Father : NSObject-(void)jump;@end
#import "Father.h"@implementation Father-(void)jump{    NSLog(@"Father can jump 1.8m");    return ;}@end

#import "Father.h"@interface Son : Father@end

#import "Son.h"@implementation Son-(void)jump{    NSLog(@"Son can jump 1.6m");    return ;}@end

////  main.m//  继承(虚方法)////  Created by X-Liang on 14-4-9.//  Copyright (c) 2014年 X-Liang. All rights reserved.//#import <Foundation/Foundation.h>#import "Father.h"#import "Son.h"int main(int argc, const char * argv[]){    @autoreleasepool {        //父类的指针可以指向子类的对象        //虚方法:调用时不看指针看对象的方法为虚方法        //OC 中对象的调用都是不看指针看对象,所以OC中的方法为虚方法        //不同事物被相同事件触发,产生不同结果        Son *son=[[Son alloc] init];        Father *p=son;        //调用的是子类的jump方法,调用方法是不看指针,看对象,对象的地址调用对象的方法        //虽然是Father的指针,但是Son对象的地址        //对象的地址调用对象的方法        [p jump];    }    return 0;}

例子:

体现不同对象相同事件触发时,产生不同结果

#import <Foundation/Foundation.h>@interface Animal : NSObject-(void)BeBeatn;//表示被打时的响应@end#import "Animal.h"@implementation Animal-(void)BeBeatn{    return ;}@end#import "Animal.h"@interface Cat : Animal@end#import "Cat.h"@implementation Cat-(void)BeBeatn{    NSLog(@"Brak ank jump to hight");    return ;}@end#import "Animal.h"@interface Dog : Animal@end#import "Dog.h"@implementation Dog-(void)BeBeatn{    NSLog(@"Give a hard bit");    return ;}@end#import "Animal.h"@interface Forg : Animal@end#import "Forg.h"@implementation Forg-(void)BeBeatn{    NSLog(@"Do nothing");    return ;}@end#import <Foundation/Foundation.h>#import "Animal.h"//#import "Cat.h"//#import "Dog.h"//#import "Forg.h"@interface Human : NSObject//如果没有虚方法的话,需要声明三个函数//-(void)BeatDog:(Dog *)dog;//-(void)BeatCat:(Cat *)cat;//-(void)BeatForg:(Forg *)forg;//因为父类指针可以指向子类,所以可以仅声明一个BeatAnimal方法即可,传递Animal指针-(void)BeatAnimal:(Animal *)animal;//形参为*Animal,为父类指针,可以指向Dog,Cat,Forg对象 @end#import "Human.h"@implementation Human-(void)BeatAnimal:(Animal *)animal{    NSLog(@"Beat %@",[animal class]);//输出Animal的类名    [animal BeBeatn];    return ;}@end

#import <Foundation/Foundation.h>#import "Dog.h"#import "Cat.h"#import "Animal.h"#import "Human.h"#import "Forg.h"int main(int argc, const char * argv[]){    @autoreleasepool {                // insert code here...        // NSLog(@"Hello, World!");        Forg *forg=[[Forg alloc] init];        Dog *dog=[[Dog alloc] init];        Cat *cat=[[Cat alloc] init];        Human *xiaoming=[[Human alloc] init];        //Animal *animal=[[Animal alloc] init];        [xiaoming BeatAnimal:dog];        [xiaoming BeatAnimal:forg];        [xiaoming BeatAnimal:cat];    }    return 0;}


0 0
原创粉丝点击