EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Objective C

Inheritance in Objective-C

Inheritance is a programming concept where a subclass or child class derives attributes and methods from a parent or superclass. This enables code reuse and allows subclasses to extend or override the behavior of the superclass. In Objective-C, inheritance is implemented using the class syntax. A class inheriting from another class is known as a “subclass,” while the inherited class is called the “superclass.”

Syntax for Subclass Declaration:

@interface SubclassName : SuperclassName
// Additional methods and properties for the subclass
@end

A subclass inherits all the instance variables, properties, and methods from its superclass. Moreover, a subclass can override methods from the superclass to provide its own implementation.

Example Program:

#import <Foundation/Foundation.h>

@interface Vehicle : NSObject {
    NSString *model;
    NSInteger year;
}

- (id)initWithModel:(NSString *)modelName andYear:(NSInteger)modelYear;
- (void)displayDetails;

@end

@implementation Vehicle

- (id)initWithModel:(NSString *)modelName andYear:(NSInteger)modelYear {
    model = modelName;
    year = modelYear;
    return self;
}

- (void)displayDetails {
    NSLog(@"Model: %@", model);
    NSLog(@"Year: %ld", year);
}

@end

@interface Car : Vehicle {
    NSString *fuelType;
}

- (id)initWithModel:(NSString *)modelName andYear:(NSInteger)modelYear andFuelType:(NSString *)type;
- (void)displayDetails;

@end

@implementation Car

- (id)initWithModel:(NSString *)modelName andYear:(NSInteger)modelYear andFuelType:(NSString *)type {
    self = [super initWithModel:modelName andYear:modelYear];
    if (self) {
        fuelType = type;
    }
    return self;
}

- (void)displayDetails {
    [super displayDetails];
    NSLog(@"Fuel Type: %@", fuelType);
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"Vehicle Information:");
        Vehicle *vehicle = [[Vehicle alloc] initWithModel:@"Sedan" andYear:2020];
        [vehicle displayDetails];

        NSLog(@"Car Details:");
        Car *car = [[Car alloc] initWithModel:@"SUV" andYear:2023 andFuelType:@"Diesel"];
        [car displayDetails];
    }
    return 0;
}

Output:

Vehicle Information:
Model: Sedan
Year: 2020
Car Details:
Model: SUV
Year: 2023
Fuel Type: Diesel

Output:

The product of a and b is: 56
End of lesson.