I have experience with object-oriented programming however this situation is unfamiliar for some reason. Consider the following Objective-c 2.0 code:
@interface A : NSObject
@end
@implementation A
- (void) f {
[self g];
}
@end
@interface B : A
@end
@implementation B
- (void) g {
NSLog(@"called g...");
}
@end
Is this the correct way to call a method on a child class from a method in the parent class? What happens if another child class doesn't implement method g
? Perhaps there's a better way to solve this like an abstract method in the parent class A
?
Use of super with methods This is used when we want to call the parent class method. So whenever a parent and child class have the same-named methods then to resolve ambiguity we use the super keyword.
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.
A child class can access the data members of its specific base class, i.e., variables and methods. Within this guide, we will be discussing different ways to execute or call the base call function in C++.
The key is to have a method in the parent class that may be overriden in the child class.
@interface Dog : NSObject
- (void) bark;
@end
@implementation Dog
- (void) bark {
NSLog(@"Ruff!");
}
@end
@interface Chihuahua : Dog
@end
@implementation Chihuahua
- (void) bark {
NSLog(@"Yipe! Yipe! Yipe!");
}
@end
You see, your child class will override the parent method with its own implementation. You might see it used like this:
Dog *someDog = [Chihuahua alloc] init] autorelease];
[someDog bark];
Output: Yipe! Yipe! Yipe!
You should implement g
in the parent class, but make it do nothing. This way it can be called without error, but still can be overridden.
@interface A : NSObject
@end
@implementation A
- (void) f {
[self g];
}
- (void) g {} // Does nothing in baseclass
@end
@interface B : A
@end
@implementation B
- (void) g {
NSLog(@"called g...");
}
@end
Or you check for the method on the object before executing it.
if ([self respondsToSelector:@selector(g)]) {
[self performSelector:@selector(g) withObject:nil];
}
But that can get pretty ugly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With