方法重载:相同的方法名称 不同的参数个数或类型构成方法重载。 OC没有方法重载
// // Animal.h #import <Foundation/Foundation.h> @interface Animal : NSObject -(void)run; -(void)play; @end #import "Animal.h" @implementation Animal -(void)run{ NSLog(@"run..."); } -(void)play{ NSLog(@"play..."); } @end
// // Cat.h #import <Foundation/Foundation.h> #import "Animal.h" @interface Cat : Animal @end #import "Cat.h" @implementation Cat -(void)run{ NSLog(@"猫猫run..."); } -(void)play{ NSLog(@"猫猫play..."); } @end
// // Dog.h #import <Foundation/Foundation.h> #import "Animal.h" @interface Dog : Animal @end // // Dog.m #import "Dog.h" @implementation Dog -(void)run{ [super run]; //这里可以调用父类的run方法 NSLog(@"狗狗run...");//重写了父类方法 } -(void)play{ NSLog(@"????play..."); } @end
// // main.m #import <Foundation/Foundation.h> #import "Cat.h" #import "Dog.h" int main(int argc, const char * argv[]) { @autoreleasepool { Cat *cat = [[Cat alloc]init]; [cat run];//首先从Cat类中寻找方法 找不到在从cat的超类中寻找 重写父类方法就可以写在cat方法里 [cat play]; Dog *dog = [[Dog alloc]init]; [dog run]; [dog play]; } return 0; }
时间: 2024-10-05 22:50:50