Can we create a method having the same name as the class name (just like constructor) in Java ?


Yes, we can define a method having same name as the class name.



class Prog_Prashn
{
 Prog_Prashn() // constructor
 {
 System.out.println(“ I’m the Constructor of the Class. ”);
 }
 void Prog_Prashn() // method
 {
 System.out.println(“ I’m an ordinary Method. ”);
 }
 public static void main(String a[])
 {
 Prog_Prashn obj= new Prog_Prashn(); // constructor called
 obj. Prog_Prashn(); // method called
 }
}


OUTPUT :


I’m the Constructor of the Class.
I’m an ordinary Method.

NOTE :
  • Constructor have same name as the name of a class but does not have any return type (not even void).
  • Method (function) having same name as class name is not allowed in C++.