Objective-C Language
Erfenis
Zoeken…
Syntaxis
- @interface afgeleide-klassennaam: basis-klassennaam
Auto is geërfd van voertuig
Beschouw een basisklasse voertuig en de afgeleide klasse auto als volgt:
#import <Foundation/Foundation.h>
@interface Vehicle : NSObject
{
NSString *vehicleName;
NSInteger vehicleModelNo;
}
- (id)initWithName:(NSString *)name andModel:(NSInteger)modelno;
- (void)print;
@end
@implementation Vehicle
- (id)initWithName:(NSString *)name andModel:(NSInteger)modelno{
vehicleName = name;
vehicleModelNo = modelno;
return self;
}
- (void)print{
NSLog(@"Name: %@", vehicleName);
NSLog(@"Model: %ld", vehicleModelNo);
}
@end
@interface Car : Vehicle
{
NSString *carCompanyName;
}
- (id)initWithName:(NSString *)name andModel:(NSInteger)modelno
andCompanyName:(NSString *)companyname;
- (void)print;
@end
@implementation Car
- (id)initWithName:(NSString *)name andModel:(NSInteger) modelno
andCompanyName: (NSString *) companyname
{
vehicleName = name;
vehicleModelNo = modelno;
carCompanyName = companyname;
return self;
}
- (void)print
{
NSLog(@"Name: %@", vehicleName);
NSLog(@"Model: %ld", vehicleModelNo);
NSLog(@"Company: %@", carCompanyName);
}
@end
int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Base class Vehicle Object");
Vehicle *vehicle = [[Vehicle alloc]initWithName:@"4Wheeler" andModel:1234];
[vehicle print];
NSLog(@"Inherited Class Car Object");
Car *car = [[Car alloc]initWithName:@"S-Class"
andModel:7777 andCompanyName:@"Benz"];
[car print];
[pool drain];
return 0;
}
Wanneer de bovenstaande code wordt gecompileerd en uitgevoerd, levert dit het volgende resultaat op:
2016-09-29 18: 21: 03.561 Inheritance [349: 303] Voertuigklasse basisklasse
2016-09-29 18: 21: 03.563 Overerving [349: 303] Naam: 4Wheeler
2016-09-29 18: 21: 03.563 Overerving [349: 303] Model: 1234
2016-09-29 18: 21: 03.564 Overerving [349: 303] Inherited Class Car Object
2016-09-29 18: 21: 03.564 Overerving [349: 303] Naam: S-Klasse
2016-09-29 18: 21: 03.565 Overerving [349: 303] Model: 7777
2016-09-29 18: 21: 03.565 Overerving [349: 303] Bedrijf: Benz
Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow