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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 23-Apr-2018 08:42:18
Advertisements