I have just started learning Objective-C, I am reading Programming in Objective-C 3rd Edition by Stephen G. Kochan.
There's a paragraph explaining the polymorphism mechanism:
At runtime, the Objective-C runtime system will check the actual class of the object stored inside dataValue1(an id object) and select the appropriate method from the correct class to execute. However, in a more general case, the compiler might generate the incorrect code to pass arguments to a method or handle its return value.This would happen if one method took an object as its argument and the other took a floating-point value, for example. Or if one method returned an object and the other returned an integer, for example. If the inconsistency between two methods is just a different type of object (for example, the Fraction’s add: method takes a Fraction object as its argument and returns one, and the Complex’s add: method takes and returns a Complex object), the compiler will still generate the correct code because memory addresses (that is, pointers) are passed as references to objects anyway.
I don't quite get it that the first part of the paragraph says that the compiler might generate incorrect code if I declare 2 methods in different classes with the same name and different type of arguments. while the last part of the paragraph says that it is fine to have 2 methods with the same name and different arguments and return types...oh no...
I have the following code and they compile and run fine:
@implementation A
- (int) add:(int)a {
return 1 + a;
}
@end
@implementation B
- (int) add: (B*) b {
return 100;
}
@end
id a = [[A alloc] init];
id b = [[B alloc] init];
NSLog(@"A: %i, B %i", [a add:100], [b add:b]);
Edit: As the text I cited, the code above is supposed to cause errors, but it only produces some warning messages, Multiple methods named "add:" found, Incompatible pointer to integer conversion sending "id" to parameter of type "int"
I have Java and C++ background, I know polymorphism in Objective-C is slightly different from that of those languages but I am still confused about the uncertainty(text in bold).
I think I must have misunderstood something, would you please explain in more detail about dynamic binding in Objective-C for me and those who need it?
Thanks you!