Can we define multiple methods in a class with the same name in Java?


Yes, we can define multiple methods in a class with the same name but with different types of parameters. Which method is to get invoked will depend upon the parameters passed.

In the below example, we have defined three display methods with the same name but with 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

Updated on: 24-Nov-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements