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

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki