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 CodingDots
{
 CodingDots() // constructor
 {
 System.out.println(“ I’m the Constructor of the Class. ”);
 }
 void CodingDots() // method
 {
 System.out.println(“ I’m an ordinary Method. ”);
 }
 public static void main(String a[])
 {
 CodingDots cd= new CodingDots(); // constructor called
 cd.CodingDots(); // 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++.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *