父类定义
@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
@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] 驾驶员小张在驾驶卡车