1、定义Car类
//Car.h文件
#interface Car : NSObject
{
NSString *_brand;//商标
NSString *_color;//颜色
}
- (void)setBrand:(NSString *)brand;//设置器,设置商标
- (void)setColor:(NSString *)color;//设置器,设置颜色
- (void)run;//方法,汽车加速
- (void)stop;//方法,刹车
@end
//Car.m文件
@implementation Car
- (void)setBrand:(NSString *)brand
{
_brand = brand;
}
- (void)setColor:(NSString *)color
{
_color = color;
}
- (void)run
{
NSLog(@"汽车加速了!");
}
- (void)stop
{
NSLog(@"汽车刹车了!");
}
@end//以上是.h文件内的方法实现
2、定义Taxi类(Car的子类)
//Taxi.h文件
#import "Car.h"
@interface Taxi : Car
{
NSString *_company;
}
- (void)setCompany:(NSString *)company;//设置公司方法定义
- (void)print;//打印发票的定义
@end
//Taxi.m文件
#import "Taxi.h"
@implementation Taxi
- (void)setCompany:(NSString *)company
{
_company = company;
}
- (void)print
{
NSLog(@"品牌为%@、颜色为%@、隶属于@的汽车开始打印发票了!",_brand,_color,_company);
}
@end
3、定义Truck类(也是Car的子类)
//Truck.h文件
#import "Car.h"
@interface Truck : NSObject
{
float _weight;//最大载重量
}
- (instancetype)initWeight:(float)weight;//自定义初始化方法
- (void)unload;
@end;
//Truck.m文件
#import "Truck.h"
@implementation Truck
- (instacetype)initWeight:(float)weight
{
if (self = [super init])
{
_weight = weight;
}
return self;
}
- (void)unload
{
NSLog(@"品牌为%@,颜色为%@,载重为%.2f的卡车开始卸货了!",_brand,_color,_weight);
}
4、定义main函数
int main()
{
Taxi *taxi = [[Taxi alloc] init];
[taxi setBrand:@"东风"];//
return 0;
}