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.

Example

Live Demo

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

Output

This is a constructor

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements