
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we define a method name same as class name in Java?
A method is a collection of statements that are grouped together to perform an operation. In Java, you can define a method having the same name as the class but it is not recommended as per the coding standard.
Can We define a Method Having Same as Class?
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 of a Method Having Same Name as Class
Below is an example to define a method with same name as that of class name in Java:
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); 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
Is It Recommended?
No, defining a method name same as class name in Java is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.