Image

Java - Core Java - Constructor

Constructor

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements (i.e. instructions) that are executed at time of Object creation.

Constructor is invoked at the time of object or instance creation.

class Demo
{   
  .......
  // A Constructor
  new Demo() {}
  .......
}
 
// We can create an object of above class and calls above constructor.
Demo obj = new Demo();

Rules for writing Constructor:

Constructor(s) of a class must have the same name as the class name in which it resides. A constructor in Java can not be abstract, final, static and synchronized. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

Types of constructor

There are two type of constructor in Java:
  • No-argument constructor
  • Parameterized Constructor
  • 1. No-argument constructor

    A constructor that has no parameter is known as default constructor. If we don’t define a constructor in a class, then compiler creates default constructor (with no arguments) for the class and if we write a constructor with arguments or no-argument then compiler does not create default constructor. Default constructor provides the default values to the object like 0, null etc. it is depending on the type.

    Program to demonstrate default constructor
    import java.io.*;
    class Demo
    {
        int num;
        String name;
        // this would be invoked while object of that class created.
        Demo()
        {
            System.out.println("Constructor called");
        }
    }
    class H4C
    {
        public static void main (String[] args)
        {
            // this would invoke default constructor.
            Demo Demo1 = new Demo();
            // Default constructor provides the default values to the object like 0, null
            System.out.println(Demo1.name);
            System.out.println(Demo1.num);
        }
    }
    2. Parameterized Constructor

    A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with your own values, then we can use parameterized constructor.

    Program to demonstrate parameterized contructor
    import java.io.*;
    class Demo
    {
        // data members of the class.
        String name;
        int id;
        // parameterized contructor
        Demo(String name, int id)
        {
            this.name = name;
            this.id = id;
        }
    }
     
    class H4C
    {
        public static void main (String[] args)
        {
            // this would invoke parameterized constructor.
            Demo Demo1 = new Demo("ashish", 1);
            System.out.println("DemoName :" + Demo1.name + " and DemoId :" + Demo1.id);
       }
    }

    Constructor Overloading

    Sometimes there is need to initialize an object in different ways, this can be done by using constructor overloading.

    class Box
    {
        double width, height, depth;
        Box(double w, double h, double d)
        {
            width = w;
            height = h;
            depth = d;
        }
        Box()
        {
            width = height = depth = 0;
        }
        Box(double len)
        {
            width = height = depth = len;
        }
        double volume()
        {
            return width * height * depth;
        }
    }
     
    public class Test
    {
        public static void main(String args[])
        {
            // constructors
            Box mybox1 = new Box(10, 20, 15);
            Box mybox2 = new Box();
            Box mycube = new Box(7);
     
            double vol;
     
            // volume of first box
            vol = mybox1.volume();
            System.out.println(" Volume of mybox1 is " + vol);
     
            // volume of second box
            vol = mybox2.volume();
            System.out.println(" Volume of mybox2 is " + vol);
     
            // volume of cube
            vol = mycube.volume();
            System.out.println(" Volume of mycube is " + vol);
        }
    }
     
    Note:
  • Constructor calling should be the first statement of constructor in Java.
  • If we defined any parameterized constructor, then compiler won't create default constructor and if we don’t define any constructor, then compiler creates the default constructor during compilation
  • Recursive constructor calling is not valid in java.