Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Constructor and Its Types

October 15th 2020   18

Constructor and Its Types
Constructor and Its Types

Constructor:

Constructors are used for initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. Every time an object is created using the new() keyword, at least one constructor is called to assign initial values to the data members of the same class. It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because the java compiler creates a default constructor if your class doesn't have any.

java constructor example code

Rules for writing constructor:

rules for writing constructor with example code

Types of constructor:

  • No-argument constructor: 

no argument constructor example code

 

  • Parameterized Constructor: 

parameterized constructor example code

#Note

  1. If any assignment is not made to any class variable in both the constructor, default values are provided to class variables of the object like 0, null, etc depending on the data type. 
  2. There are no “return value” statements in constructor, but constructor returns current class instance. We can write ‘return’ inside a constructor. Constructor(s) do not return any type while method(s) have the return type or void if does not return any value.
  3. Constructor Overloading is possible.