Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Method Overloading

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?

like image 642
EmptyStack Avatar asked Feb 10 '11 07:02

EmptyStack


People also ask

Does Objective-C support method overloading?

Method overloading is a programming language feature supported by Objective-C, C++, Java, and a few other languages.

What is method overloading give example?

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() { ... }

What is the difference between overloading and overriding?

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.

What is an overloaded method C#?

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.


2 Answers

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;
like image 141
Michael Aaron Safyan Avatar answered Oct 29 '22 06:10

Michael Aaron Safyan


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.

like image 44
bbum Avatar answered Oct 29 '22 04:10

bbum