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

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 20-Aug-2019 12:56:48
Advertisements