CodesJava

Easy learning with example program codes

Why default constructor is used?


Default or no-argument constructor

A constructor with no parameter is known as default or no-argument constructor. If no constructor is defined in the class then compiler automatically creates a default constructor at the time of compilation.

Syntax:

Class_name(){
       //optional block of code
}

Why default constructor is used?

Default constructor is used to provide default values to the object properties i.e. to provide default state of an object.

Example

/**
 * This program is used to show the use of default constructor.
 * @author CodesJava
 */
public class ConstructorExample1 {
                int num;
                String str;
                ConstructorExample1(){
                       System.out.println("Constructor called.");
                }
 
                public static void main(String args[]){
                       //constructor call
                       ConstructorExample1 obj1 = 
                                      new ConstructorExample1();
 
                       //print default values of object properties.
                       System.out.println("num = " + obj1.num);
                       System.out.println("str = " + obj1.str);
                }
}

Output

Constructor called.
num = 0
str = null

Java interview questions on main method



Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap