×
☰ See All Chapters

Constructor in java

  1. Constructor is a special method which has the same name as class name. It does not have a return type even void also. 

  2. As the name states, constructor is used to construct the object. An object can never be created without invoking a constructor. Constructors are used to initialize the instance variable or to initialize the state of the object. 

  3. Constructor is always executed only once during the creation of every new object. 

  4. Constructor can be invoked only with the help of “new” keyword and can never be accessed with the help of dot (“.”) operator or it can never be invoked by an object. 

  5. If you have not written a constructor in a class, a default constructor with no arguments is added in “.class” file by the compiler during compilation time.  If you write any constructor in a class then the compiler will not add any default constructor. 

  6. Constructor can be overloaded.  

  7. Constructor can have vararg.  

  8. Constructor can have access specifiers (private, protected or public). 

  9. Constructor cannot have modifiers like abstract, static and final keywords. 

  10. Constructors are not inherited into sub class(sub class will be studied in later chapters) 

Default constructor syntax

Access_specifier  ClassName ()

{

//Constructor body

}

Syntax to create object: ClassName classVar = new ClassName();

Parameterized constructor syntax

Access_specifier  ClassName (type1 pmtr1, type2 pmtr2, type3 pmtr3..)

{

//Constructor body

}

Syntax to create object: ClassName classVar = new ClassName(arg1, arg2, arg3..);

Example

package com.java4coding;

 

public class ConstructorDemo {

       

        public ConstructorDemo ( ) {

                System.out.println("Default Constructor");

        }

       

        public ConstructorDemo (String message ) {

                System.out.println("Parameterized Constructor");

        }

       

        public ConstructorDemo (int num) {

                System.out.println("Parameterized Constructor");

        }

       

        public static void main(String... args) {

                ConstructorDemo constructorDemo1 = new ConstructorDemo();

               

                ConstructorDemo constructorDemo2 = new ConstructorDemo("Hello");

               

                ConstructorDemo constructorDemo3 = new ConstructorDemo(100);

        }

}

What if constructor is made private?

We cannot create the object for the class having private constructor.  To create an object for any class, constructor of the class should be accessible.

What is good practice of writing parameterized constructor?

When we write parameterized constructor, it is a good practice to write default constructor explicitly. Many APIs and libraries rely upon default constructor.

 


All Chapters
Author