Should a constructor always have the same name as the class in java?

Yes, the constructor should always have the same name as the class.

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.

If the programmer doesn’t write a constructor the compiler writes a constructors on his behalf.


Live Demo

public class Sample{
   public Sample(){
      System.out.println("This is a constructor");
   public static void main(String args[]){
      Sample obj = new Sample();


This is a constructor
Vikyath Ram
Vikyath Ram

A born rival