------ Java培训、Android培训、iOS培训、.Net培训期待与您交流! ------
http://www.itheima.com
- self用在对象方法中,谁调用当前方法,self就指代谁,例如:
-(void)eat{
[self run];
}
- self用在类方法中,谁调用当前方法,self就指代谁,例如:
+(void)eat{
[self run];
}
在此段代码中如果是用人的类Person调用eat方法,那么self就指代Person类。- self修饰变量,例如:
self->age = age;
}
- 多态的概念:不同的对象以自己的方式响应父类同名的方法,这就是多态。
- 多态的条件:有继承关系、有方法重写、父类的声明变量指向子类对象。
- 多态的代码体现形式:Animal *ani = [Dog new];在此段代码中父类Animal声明的变量ani指向了子类Dog的对象。
- 为什么使用多态:下面通过一个人骑自行车的例子来说明:
//自行车类的声明
#import <Foundation/Foundation.h>
@interface Bike : NSObject
-(void)run;
@end
//自行车类的实现
#import "Bike.h"
@implementation Bike
-(void)run{
NSLog(@"自行车在跑");
}
@end
//子类黑色自行车的声明
#import "Bike.h"
@interface Blackbike : Bike
@end
//子类黑色自行车的实现
#import "Blackbike.h"
@implementation Blackbike
-(void)run{
NSLog(@"黑色自行车在跑");
}
@end
//子类白色自行车的声明
#import "Bike.h"
@interface Whitebike : Bike
@end
//子类白色自行车的实现
#import "Whitebike.h"
@implementation Whitebike
-(void)run{
NSLog(@"白色自行车在跑");
}
@end
//人的类的声明
#import <Foundation/Foundation.h>
#import"Bike.h"
@interface Person : NSObject
//父类和子类同用方法名run !!!
-(void)run:(Bike*)bike;
@end
//人的类的实现
#import "Person.h"
@implementation Person
-(void)run:(Bike*)bike{
[bike run];
}
@end
//main.m文件代码
#import <Foundation/Foundation.h>
#import"Person.h"
#import"Blackbike.h"
#import"Whitebike.h"
int main(int argc,const char * argv[]) {
@autoreleasepool {
Person *p = [Personnew];
Blackbike *black = [Blackbikenew];
Whitebike *white = [Whitebikenew];
[p run:black];
[p run:white];
}
return 0;
}
//人的类的声明
#import <Foundation/Foundation.h>
#import"Blackbike.h"
#import"Whitebike.h"
@interface Person : NSObject
//需要声明两个不同名的方法!!!
-(void)rideBlackBike:(Blackbike *)black;
-(void)rideWhiteBike:(Whitebike *)white;
@end
#import "Person.h"
@implementation Person
-(void)rideBlackBike:(Blackbike *)black{
[black run];
}
-(void)rideWhiteBike:(Whitebike *)white{
[white run];
}
@end
//相应的main.m文件
#import <Foundation/Foundation.h>
#import"Person.h"
#import"Blackbike.h"
#import"Whitebike.h"
int main(int argc,const char * argv[]) {
@autoreleasepool {
Person *p = [Personnew];
Blackbike *black = [Blackbikenew];
Whitebike *white = [Whitebikenew];
[p rideBlackRun:black];
[p rideWhiteRun:white];
}
return 0;
}
从这个对比中我们可以感受到使用多态可以实现简化编程接口的作用,试想如果再多出一辆蓝色自行车,在不使用多态的情况下还需要在Person类中定义一种方法,这样会使程序冗余;同时此程序还可体现出多态可实现类和类之间重用方法名。