What types of method overload are there?

1.6 Method overloading

  

Open up the following simple program by moving the mouse over the program lines:


Rollover image

 Methods of the same name

As you have probably noticed, the MethodOverloaded class contains two methods that are addressed by the same name, javaMethods.

In Java, several methods can be defined in a class, the names of which are identical, but which differ from one another in terms of the number and / or type of arguments. We refer to this programming style in Java as overloading.

 
definition

Overloaded

Overloading means that two methods with the same name but different parameters can be declared in one class. When the method is called, the compiler then recognizes which method is meant based on the number and type of parameters.

 Fig .: Overloading of methods Same name but different signature

However, it is not permitted to define two methods in a class with the same name and identical parameter list, i.e. the same signature.

 
definition

signature

The signature of a method is made up of the method name and the sequence of its parameter types in the method head.

 The parameter type and number are decisive

The types of parameters and the number are decisive for the compiler. Not the name of the parameters. You should always pay attention to this.

In our example, the two methods of the method Overload class have the following signature:

  • java methods String
  • javaMethods String int

The compiler compares the types of parameters in the method headers with the types of values ​​specified in a particular method call. If the compiler cannot assign the parameters in the individual methods (same parameter lists), it outputs an error message. This also applies to methods that only differ in the type of their return value.


Slide show


  

The user of an object can use the possibility of overloading methods to select a particular method that most closely matches the requirements of his specific task.