Home >Java >javaTutorial >In Java, can we define multiple methods with the same name?

In Java, can we define multiple methods with the same name?

PHPz
PHPzforward
2023-09-03 09:21:07708browse

In Java, can we define multiple methods with the same name?

Yes, we can define multiple methods with the same name but different parameter types in a class. Which method is called will depend on the arguments passed.

In the example below, we define three display methods with the same name but different parameters. Depending on the parameters, the appropriate method will be called.

Example

public class MethodWthSameNameTest {
   public void display() { // method with no parameters
      System.out.println("display() method with no parameter");
   }
   public void display(String name) { // method with a single parameter
      System.out.println("display() method with a single parameter");
   }
   public void display(String firstName, String lastName) { // method with multiple parameters
      System.out.println("display() method with multiple parameters");
   }
   public static void main(String args[]) {
      MethodWthSameNameTest test = new MethodWthSameNameTest();
      test.display();
      test.display("raja");
      test.display("raja", "ramesh");
   }
}

Output

display() method with no parameter
display() method with a single parameter
display() method with multiple parameters

The above is the detailed content of In Java, can we define multiple methods with the same name?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete