Turn Desktop View Off
by Dinesh Thakur

Each time an object is created, a Constructor is always invoked. In the previous program, the constructor we created was invoked. But in the programs that we made earlier, we did not create any constructor. So in such situations, the compiler automatically writes one for you. This constructor is known as the default constructor. It does not contain any parameters nor does it contain any statements in its body. Its only purpose is to enable you to create object of class type. The default constructor looks like

public Rectangle(){ }

When the compiler creates a default constructor; it does nothing. The objects created by the default constructor will have fields with their default values. It should be remembered that constructors are invoked only after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializes are executed.

class Display

{
       int a=9; //initializer expression
       int b=4; //initializer expression
       int c;   //assigned default value
       Display()
       {
     
         a=4; //override default and initializer expression
       }
       void show()
       {
         System.out.println("Value of a : " +a);
         System.out.println("Value of b : " +b);
         System.out.println("Value of c : " +c);
       }
}
   class DefaultConstructor
{
     public static void main(String[] args)
     {
       Display data=new Display();
       data.show();
     }
}

Default Constructor in Java with Example