Can we define a method name same as class name in Java?


Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.

Example

Live Demo

public class MethodNameTest {
   private String str = "Welcome to TutorialsPoint";
   public void MethodNameTest() { // Declared method name same as the class name
      System.out.println("Both method name and class name are the same");
   }
   public static void main(String args[]) {
      MethodNameTest test = new MethodNameTest();
      System.out.println(test.str);
      System.out.println(test.MethodNameTest());
   }
}

In the above example, we can declare a method name (MethodNameTest) same as the class name (MethodNameTest), it will be compiled successfully without any errors.

Output

Welcome to TutorialsPoint
Both method name and class name are the same

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements