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
Release: 2023-09-03 09:21:07
forward
707 people have browsed it

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");
   }
}
Copy after login

Output

display() method with no parameter
display() method with a single parameter
display() method with multiple parameters
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template