Constructor in Java

  • Constructor is a special method which is used to
    initialize the state of an object.
  • Constructor is special method because it has following
    properties:
– Automatically called
– Constructor name is same as class name
– No return type
  • Programmer can’t call constructor explicitly. It is called
    automatically at the time of creation of object.
  • Constructor implicitly returns this (reference of current object).

Types of Constructor

Default Constructor

Default constructor does not take any argument and it is
used to initialize default values of an object.

Default constructor


Parameterized Constructor

Constructor having one or more arguments is called parameterized constructor. Example of parameterized constructor is given below.


Copy Constructor

Copy constructor is a type of parameterized constructor. It
is used to copy existing object values into another object at its creation
time.

Copy Constructor
  • In java each class has constructor. If we do not write any
    constructor in our class then compiler will add a default constructor
    implicitly. This can be proved by decompiling the .class file as shown below.
Constructor in Java
  • Constructor can be overloaded same as like method overloading.
  • Constructor can be private but can’t be final (constant).
Observe below program:

constructor in java

In above program we have used temp() two times. Have you thought
how compiler differentiate between temp() and void temp()? It is done by their positions,
the first temp() is treated as constructor while the next temp() is treated as method.

Constructor Chaining

Calling one constructor form another constructor is known as
constructor chaining. Below program shows the concept of constructor chaining.

Constructor Chaining

Rules:

  • this can’t be
    used into normal method to call constructor.
  • this must be
    first line of constructor.
  • We can use constructor chaining only when object is created
    using new keyword.
  • Order of calling doesn’t matter.

Leave a Comment

Your email address will not be published. Required fields are marked *