标签:
继承部分典型例题:(主要以汽车Car为父类,Taxi为子类)
主文件main.m内容
#import <Foundation/Foundation.h> #import "Car.h" #import "Taxi.h" int main(int argc, const char * argv[]) { @autoreleasepool { Car *newCar = [Car new]; [newCar setNumber:3]; [newCar setSpeed:156]; [newCar run]; Taxi *newTaxi = [Taxi new]; [newTaxi setNumber:6]; [newTaxi setSpeed:80]; [newTaxi run]; } return 0; }
父类文件Car.h内容
#import <Foundation/Foundation.h> @interface Car : NSObject { int _number; int _speed; } -(void)setNumber:(int)number; -(void)setSpeed:(int)speed; -(void)run; @end
父类文件Car.m内容
#import "Car.h" @implementation Car -(void)setNumber:(int)number { _number = number; } -(void)setSpeed:(int)speed; { _speed = speed; } -(void)run { NSLog(@"这是Car中的run方法,%d号车跑起来了,本车时速为%dkm/h",_number,_speed); } @end
子类文件Taxi.h内容
#import <Foundation/Foundation.h> #import "Car.h" @interface Taxi : Car -(void)run; @end
子类文件Taxi.m内容
#import "Taxi.h" @implementation Taxi -(void)run{ // [super run]; NSLog(@"这是Taxi中的run方法,%d号车跑起来了,本车时速为%dkm/h",_number,_speed); } @end
标签:
原文地址:http://my.oschina.net/AnyiLi/blog/515383