I am having doubt in Objective-C Method Overloading. Java supports method overloading with the same name, same number of arguments of different types. But when I try to do similar declaration in Objective-C, it throws me the error Duplicate declaration of method. Consider the following code,
/* Java */
int add(int i, int j);
int add(int i, int j, int k); // Accepted
float add(float i, float j); // Accepted
/* Objective-C */
- (int)add:(int)i and:(int)j;
- (int)add:(int)i and:(int)j and:(int)k; // Accepted
- (float)add:(float)i and:(float)j; // Throws error
Why is this not supported in Objective-C? Is there an alternative for this?
Method overloading is a programming language feature supported by Objective-C, C++, Java, and a few other languages.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }
Overriding occurs when the method signature is the same in the superclass and the child class. Overloading occurs when two or more methods in the same class have the same name but different parameters.
In C#, there might be two or more methods in a class with the same name but different numbers, types, and order of parameters, it is called method overloading.
It simply isn't supported in Objective-C. It wasn't supported in plain old C, so it isn't all that surprising that Objective-C likewise did not add method overloading. For clarity, this can sometimes be good. Typically, the way around this is to include some information about the parameter in the function name. Ex:
- (int) addInt:(int)i toInt:(int)j;
- (int) addInt:(int)i toInt:(int)j andInt:(int)k;
- (float) addFloat:(float)i toFloat:(float)j;
Starting with this:
- (int)add:(int)i and:(int)j;
This does not override anything -- it is just another method:
- (int)add:(int)i and:(int)j and:(int)k; // Accepted
The following isn't accepted specifically because Objective-C does not allow for co-variant or contra-variant method declarations. Nor does Objective-C do type based dispatch overloading a la Java and C++.
- (float)add:(float)i and:(float)j; // Throws error
Note that Java was derived quite directly from Objective-C.
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