by Dinesh Thakur Category: Classes

If you omit implementation of a constructor within your class, a constructor added by the Java compiler, each class must have a constructor and the one used is called the default constructor. You won't see it listed anywhere in your Java code as the compiler adds at compilation time into the .class file. Should you implement a constructor in your code, the compiler not add the default one. It does not contain any parameters nor does it contain any statements in its body. Its only purpose is to enable you to create an 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



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles