Constructor in Java

It is block of code that initializes the newly created Object. It has same name as its Class. Constructor has no return type. The constructor cannot be static, abstract or Final.

public class MyClass{ //This is the constructor MyClass(){ } .. }

Types of Constructor

Default Parameter-less Parameterized

  1. Default Constructor The default constructor is created by the Java compiler when the coder does not declare any constructor for the class and this constructor does not contain any argument. The Java file does not contain any code for the default constructor. The default constructor code is created at the time of compilation of Java code and is stored in the .class file.

  2. Parameter-less Constructor When a constructor is declared without any parameter or argument, then it is called a parameter-less constructor. A parameter-less constructor works like a default constructor and this constructor can contain statements, or it can be empty.

  3. Parameterized Constructor When any constructor is declared with one or more parameters, then it is called a parameterized constructor. The parameter values of the constructor are passed at the time of object creation.

Constructor Overloading Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.