What is a method signature in Java?

Java 8Object Oriented ProgrammingProgramming

The method signature consists of the method name and the parameter list.

Example

Live Demo

public class MethodSignature {
   public int add(int a, int b){
      int c = a+b;
      return c;
   }
   public static void main(String args[]){
      MethodSignature obj = new MethodSignature();
      int result = obj.add(56, 34);
      System.out.println(result);
   }
}

Output

90

Method signature does not include the return type of the method. A class cannot have two methods with same signature. If we try to declare two methods with same signature you will get a compile time error.

public class MethodSignature {
   public int add(int a, int b){
      int c = a+b;
      return c;
   }
   public double add(int a, int b){
      double c = a+b;
      return c;
   }
   public static void main(String args[]){
      MethodSignature obj = new MethodSignature();
      int result = obj.add(56, 34);
      System.out.println(result);
   }
}

Error

C:\Sample>javac MethodSignature.java
MethodSignature.java:7: error: method add(int,int) is already defined in class MethodSignature
public double add(int a, int b){
              ^
1 error
raja
Published on 05-Feb-2018 20:24:58
Advertisements