OC面向对象 点语法 继承 重写练习

父类定义

@interface Vehicle : NSObject

{

    NSString* colour;

    int Speed;

}

@property NSString* colour;

@property int Speed;


-(void)run;

-(void)drive:(NSString *)name;


@end

父类实现方法

@implementation Vehicle

@synthesize colour;

@synthesize Speed;

-(void)run{

    NSLog(@"the Vehicle is ruuning");

}

-(void)drive:(NSString *)name {


    NSLog(@"%@在驾驶车辆",name);

}

@end

子类car 自有属性定义

@interface Car : Vehicle

{

    int numberofwheels;

}

@property int numberofwheels;

@end

子类car 方法重写

@implementation Car

@synthesize numberofwheels;

-(void)run{

    NSLog(@"the %@ car is running at the speed of %d km/h",colour,Speed);

    NSLog(@"the %@ car has %d wheels",colour,numberofwheels);

}

-(void)drive:(NSString *)name {

    

    NSLog(@"驾驶员%@在驾驶小汽车",name);

}

@end

子类truck 自有属性定义

@interface Truck : Vehicle

{ int maxweight;}

@property int maxweight;

-(void)unload;

@end

子类truck 自有方法重写

@implementation Truck

@synthesize maxweight;

-(void)unload{

    NSLog(@"卡车卸货%d",maxweight);

}

-(void)run{

    NSLog(@"the %@ truck is running at the speed of %d km/h",colour,Speed);  

}

-(void)drive:(NSString *) name{

    

    NSLog(@"驾驶员%@在驾驶卡车",name);

}

@end

驾驶员类

@interface Person : Vehicle

{NSString * name;}

@property NSString * name;

-(void)dodrive:(Vehicle *) vehicle and: (NSString *) name;



@end

驾驶方法实现

@implementation Person

@synthesize name;

-(void)dodrive:(Vehicle *) vehicle and: (NSString *) name

{

    [vehicle drive:name];

}

@end


@autoreleasepool {

        

        Car *car1=[Car alloc];

        car1.colour =@"red";

        car1.Speed = 100;

        car1.numberofwheels = 4;

        [car1 run];

        Truck *truck1 =[Truck alloc];

        truck1.colour =@"black";

        truck1.Speed = 10;

        truck1.maxweight =4;

        [truck1 unload];

        [truck1 run];

        Person *person1 = [Person alloc];

        person1.name =@"小李";

        [person1 dodrive:car1 and:person1.name];

        Person *person2 = [Person alloc];

        person2.name =@"小张";

        [person2 dodrive:truck1 and:person2.name];

        

    }

    return 0;

输出结果

2014-05-31 08:07:03.240 OC02[1066:303] the red car is running at the speed of 100 km/h

2014-05-31 08:07:03.242 OC02[1066:303] the red car has 4 wheels

2014-05-31 08:07:03.243 OC02[1066:303] 卡车卸货4

2014-05-31 08:07:03.243 OC02[1066:303] the black truck is running at the speed of 10 km/h

2014-05-31 08:07:03.243 OC02[1066:303] 驾驶员小李在驾驶小汽车

2014-05-31 08:07:03.244 OC02[1066:303] 驾驶员小张在驾驶卡车



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值