Что такое сигнатура метода в java
Перейти к содержимому

Что такое сигнатура метода в java

  • автор:

Method Signature in Java

Method Signature in java is defined as the structure of a method that is designed by the programmer. Method Signature is the combination of a method's name and its parameter list. A class cannot have two methods with the same signature. If we declare two methods with the same signature, compilation error is thrown.

Method signature does not include the return type of a method.

Why do we need a Method Signature in Java?

Let's suppose you want to declare two methods of the same name for example getArea , the first method is used to find the area of a rectangle, and another method of the same name is used to find the area of a square.

How can you define two methods of the same name? The answer is to use different method signatures of both methods. We can declare two methods of same name by creating a difference in the parameter list of both methods. Two parameter lists are different if either of the following conditions are satisfied:

  • Different number of parameters in both parameter lists
  • At least one parameter is of different type

This event of declaring two methods with same name but different parameter lists (or signature) is called Method Overloading.

An example of Method Overloading is provided below. You can notice, there are two methods with same name sum but different number of parameters.

Let's understand how to implement method signature in java.

Example of Method Overloading

In the example below, we are creating two methods of the same name i.e getArea with method signatures. The first method is used to calculate the area of a rectangle, and the second method is used to calculate the area of a square.

Output:

Example 1: Java Method Signature

In Java, we can have four forms of method signatures. Let's understand each of them one by one.

Without return type and no parameters.

In this form, the method doesn't have its return type i.e the return type is void and without a parameter.

The printName() method doesn't have any return type and parameter in the below example.

Output:

Without Return Type and with Parameter.

In this form, the method doesn't have its return type i.e the return type is void but contains parameters.

The printName() method doesn't have any return type but contains a parameter of String type.

Output:

With return type and no parameter

In this form, the method has its return type but without any parameters.

Output:

With return type and with Parameter.

In this form, the method has both return type and parameters .

The printName() method has a return type of String , and also contains a parameter of String type.

Output:

Example 2: Class with Two Methods with the Same Signature

In java, we cannot implement two methods of the same signature i.e of the same method name and same parameter list. Because it will create a confusion at run time regarding which method to call. Even if the return types are different, two methods with same signatures will throw compile-time error.

Let's understand this using an example.

In the below program we are implementing two methods of the same signature. Let's see what will happen when we try to execute our program.

Output:

Learn More

We can learn more about Java Methods and their characteristics through this article: Methods in Java

Что такое сигнатура метода?

Что такое сигнатура метода и отличие от спецификация и контракта метода?

Определение. Два компонента объявления метода включают сигнатуру методаимя метода и параметры.

Пример метода, описанного определения выше:

Cигнатура метода в сочетании с типом возвращаемого значения называется контрактом метода.

Спецификация метода может рассматриваться как документация для метода.

Итог:

public void moveTo(int x, int y) throws IOException — сигнатура

public void moveTo(int x, int y) throws IOExceptionконтракт

Definition of a Java Method Signature

In Java, a method signature is part of the method declaration. It’s the combination of the method name and the parameter list.

The reason for the emphasis on just the method name and parameter list is because of overloading. It’s the ability to write methods that have the same name but accept different parameters. The Java compiler is able to discern the difference between the methods through their method signatures.

Method Signature Examples

The method signature in the above example is setMapReference(int, int). In other words, it's the method name and the parameter list of two integers.

The Java compiler will let us add another method like the above example because its method signature is different, setMapReference(Point) in this case.

In our last example of a Java method signature, if you follow the same rules as the first two examples, you can see that the method signature here is calculateAnswer(double, int, double, double).

Java Method Signature

In this post, we are going to talk about the Java method signature, method overloading, and method overriding by examples. The JDK version we use to compile the source code in this example is OpenJDK 13 and the IDE we use is Eclipse IDE 2020-03.

1. What is a method signature in Java

In Java programming language, the method signature consists of two parts: the method’s name and the parameter list. These two parts are part of a method declaration. The parameter list includes the number, type, and order of parameters but not the name of the parameter. The name of the parameter is ignored by the compiler for checking method uniqueness. Return types and exception lists are not part of the method signature.

For example, the following four methods are considered to be the same:

This is because they have the same method signature hello(String) .

However, the following two methods have distinct signatures and are considered to be different methods:

This is because the first method’s signature is hello(String) but the second method’s signature is hello(CharSeequence) .

Note that both method names and parameter names are “identifiers” in Java, They share the same rules regarding valid names. You can have a look at §3.8 from the Java Language Specification to find out exactly what an identifier may contain. In addition, all keywords in Java are reserved and cannot be used as a method name or a parameter name. You can find all keywords in Java at §3.9 from the Java Language Specification.

2. Polymorphism

Polymorphism means “multiple forms”. In object-oriented programming languages like Java, polymorphism means we can use one single interface to represent various classes. There are two types of polymorphism in Java: compile-time and runtime. Method overloading and method overriding are two examples of polymorphism in Java.

2.1 Method Overloading

Method overloading is an example of compile-time polymorphism. It is also called “static binding”. It means methods declared in a class having the same method name but different parameter list.

In the example below, we can see that there are two methods that have the same method name “hello” but different parameters. As they have different method signatures, the Java compiler is able to differentiate them and invoke them by checking their method signatures. This is done by the compiler at compile-time, so we call it compile-time polymorphism or static binding. MethodSignatureExample.java

The output of the example is below:

2.2 Method Overriding

Method overriding is an example of runtime polymorphism. It is also called “dynamic binding”. It means the actual method to be called is not decided by the compiler at compile time but is determined at run time. When we invoke a method that has been overridden, the runtime will find out the actual method to be called. Comparing to static binding, dynamic binding is slower because the runtime needs time to figure it out correctly.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *