继承

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值