Constructor in Java

Con­struc­tor in java is one kind of method but you can not call it as method because con­struc­tor name is sim­i­lar as class name and no return type is define for con­struc­tor so you can call it as block. it is used to ini­tial­ize the object’s state. Every time you cre­ate an object using new() key­word a con­struc­tor is invoked (default con­struc­tor is only cre­at­ed by the com­pil­er if we have not cre­at­ed default con­struc­tor explic­it­ly) to assign ini­tial val­ues to the data mem­ber.

Syntax :

Exam­ple :

Rules of Constructor in java :

  1. Con­struc­tor name should be same as class name.
  2. Con­struc­tor does not sup­port abstract, final, sta­t­ic and Syn­chro­nized key­word.
  3. default con­struc­tor has same access mod­i­fi­er as the class.

Types of java constructors

There are two types of con­struc­tors in java :

  1. Default con­struc­tor (no-arg con­struc­tor)
  2. Para­me­ter­ized con­struc­tor

Default constructor

A con­struc­tor with­out para­me­ter is called as default con­struc­tor in java. If you have not cre­at­ed any con­struct in your class then default con­struc­tor will be cre­at­ed by com­pil­er if you have cre­at­ed default con­struct in java then no default con­struct is cre­at­ed by com­pil­er. Default con­struc­tor pro­vides the default val­ues to the object like 0, null etc. depend­ing on the type.

Exam­ple :

Parameterized Constructor

A con­struct with para­me­ter is called para­me­ter­ized con­struc­tor in java. If you wish to ini­tial­ize some val­ue to data mem­ber instead of default val­ue then you have to use para­me­ter­ized con­struc­tor .

Does constructor return any value ?

There are no return type is defined for con­struct, but con­struc­tor returns cur­rent class instance. You can write ‘return’ inside a con­struc­tor.

Constructor Overloading

More than one con­struc­tor with same name but with dif­fer­ent para­me­ter define in the same class is called as con­struc­tor over­load­ing in java. below is the exam­ple of con­struc­tor over­load­ing.

Exam­ple :

Constructors are not inherited

Dis­sim­i­lar to state­ment in a con­struc­tor can be inher­it­ed by sub­class­es, con­struc­tors are not inher­it­ed.

First statement in a constructor must call to this() or super()

The main procla­ma­tion of each con­struc­tor must be a call to either this() or super().

Constructors can be private

We can make a con­struc­tor pri­vate to keep the out­side world from mak­ing anoth­er instance of our class. Think about the accom­pa­ny­ing class with a pri­vate con­struc­tor.