What is process of defining two methods with same method name and parameters?

Here is an example of a typical method declaration:

public double calculateAnswer(double wingSpan, int numberOfEngines,
                              double length, double grossTons) {
    //do the calculation here
}

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.

More generally, method declarations have six components, in order:

  1. Modifiers—such as public, private, and others you will learn about later.
  2. The return type—the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name—the rules for field names apply to method names as well, but the convention is a little different.
  4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
  5. An exception list—to be discussed later.
  6. The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.

Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.


Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.


The signature of the method declared above is:

calculateAnswer(double, int, double, double)

Naming a Method

Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:

run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.

Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list.

public class DataArtist {
    ...
    public void draw(String s) {
        ...
    }
    public void draw(int i) {
        ...
    }
    public void draw(double f) {
        ...
    }
    public void draw(int i, double f) {
        ...
    }
}

Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.


Note: Overloaded methods should be used sparingly, as they can make code much less readable.


1.14. Defining Two or More Methods with the Same Name

Problem

You would like to implement two or more methods with the same name in one object. In object-oriented programming, this is called method overloading. However, in Objective-C, method overloading does not exist in the same way as it does in other programming languages such as C++.

Solution

Use the same name for your method, but keep the number and/or the names of your parameters different in every method:

- (void) drawRectangle{

  [self drawRectangleInRect:CGRectMake(0.0f, 0.0f, 4.0f, 4.0f)];

}

- (void) drawRectangleInRect:(CGRect)paramInRect{

  [self drawRectangleInRect:paramInRect
                  withColor:[UIColor blueColor]];

}

- (void) drawRectangleInRect:(CGRect)paramInRect
             withColor:(UIColor*)paramColor{

  [self drawRectangleInRect:paramInRect
                  withColor:paramColor
                  andFilled:YES];

}

- (void) drawRectangleInRect:(CGRect)paramInRect
                   withColor:(UIColor*)paramColor
                   andFilled:(BOOL)paramFilled{

  /* Draw the rectangle here */

}

This example shows a typical pattern in overloading. Each rectangle can be drawn either filled (solid color) or empty (showing just its boundaries). The first procedure is a “convenience procedure” that allows the caller to avoid specifying how to fill the rectangle. In our implementation of the first procedure, we merely call the second procedure, making the choice for the caller (andFilled:YES) The second procedure gives the caller control over filling.

Discussion

You can define two methods with the same name so long as they differ in the parameters they accept. One reasons for doing this is one function offers more customization (through parameterization) than the other function.

Method overloading is a programming language feature supported by Objective-C, C++, Java, and a few other languages. Using this feature, programmers can create different methods with the same name, in the same object. However, method overloading in Objective-C differs from that which can be used in C++. For instance, in C++, to overload a method, the programmer needs to assign a different number of parameters to the same method and/or change a parameter’s data type.

In Objective-C, however, you simply change the name of at least one parameter. Changing the type of parameters will not work:

- (void) method1:(NSInteger)param1{

  /* We have one parameter only */

}

- (void) method1:(NSString *)param1{

  /* This will not compile as we already have a
   method called [method1] with one parameter */

}

Changing the return value of these methods will not work either:

- (int) method1:(NSInteger)param1{

  /* We have one parameter only */
  return param1;

}

- (NSString *) method1:(NSString *)param1{

  /* This will not compile as we already have a
   method called [method1] with one parameter */
  return param1;

}

As a result, you need to change the number of parameters or the name of (at least) one parameter that each method accepts. Here is an example where we have changed the number of parameters:

- (NSInteger) method1:(NSInteger)param1{

  return param1;

}

- (NSString*) method1:(NSString *)param1
            andParam2:(NSString *)param2{

  NSString *result = param1;

  if ([param1 length] > 0 &&
      [param2 length] > 0){
    result = [result stringByAppendingString:param2];
  }

  return result;

}

Here is an example of changing the name of a parameter:

- (void) drawCircleWithCenter:(CGPoint)paramCenter
                       radius:(CGFloat)paramRadius{

  /* Draw the circle here */

}

- (void) drawCircleWithCenter:(CGPoint)paramCenter
                       Radius:(CGFloat)paramRadius{

  /* Draw the circle here */

}

Can you spot the difference between the declarations of these two methods? The first method’s second parameter is called radius (with a lowercase r) whereas the second method’s second parameter is called Radius (with an uppercase R). This will set these two methods apart and allows your program to get compiled. However, Apple has guidelines for choosing method names as well as what to do and what not to do when constructing methods. For more information, please refer to the “Coding Guidelines for Cocoa” Apple documentation available here.

Here is another example of two methods that draw a circle but have different names for their second parameter:

- (void) drawCircleWithCenter:(CGPoint)paramCenterPoint
               radiusInPoints:(CGFloat)paramRadiusInPoints{
  /* Draw the circle here */
}

- (void) drawCircleWithCenter:(CGPoint)paramCenterPoint
          radiusInMillimeters:(CGFloat)paramRadiusInMillimeters{
  /* Draw the circle here */
}

Here is a concise extract of the things to look out for when constructing and working with methods:

  • Have your method names describe what the method does clearly, without using too much jargon and abbreviations. A list of acceptable abbreviations is in the Coding Guidelines.

  • Have each parameter name describe the parameter and its purpose. On a method with exactly three parameters, you can use the word and to start the name of the last parameter if the method is programmed to perform two separate actions. In any other case, refrain from using and to start a parameter name. An example of the name of a method that performs two actions and uses the word and in its name is prefixFirstName:withInitials:andMakeInitialisUppercase:, where the method can prefix a first name (of type NSString) with the initials (of type NSString again) of that individual. In addition, the method accepts a boolean parameter named andMakeInitialsUppercase which, if set to YES, will prefix the first name with an uppercase equivalent of the initials passed to the method. If this parameter is set to NO, the method will use the initials it is given, without changing their case, to prefix the first name parameter.

  • Start method names with a lowercase letter.

  • For delegate methods, start the method name with the name of the class that invokes that delegate method.

What is process of defining two methods with the same method name and parameters?

The practice of defining two or more methods within the same class that share the same name but have different parameters is called overloading methods. Code section 4.22: Method overloading.

What is it called when two methods have the same name but different parameters?

Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters. When a method is called, the corresponding method is invoked by matching the arguments in the call to the parameter lists of the methods.

What is it called when two methods have the same name?

Having two or more methods named the same in the same class is called overloading.

When a method has the same name and takes the same parameters?

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.