Constructor in java

Constructor: 

Constructor is a special member of a class which is used to initialize the state of an object. It provides the values to the data members at the time of object creation that is why it is known as constructor.

Characteristics of constructor: 

  1. A constructor must have the same name as of its class.
  2. It is invoked at the time of object creation and used to initialize the state of an object.
  3. It does not have an explicit return type.

Types of constructor:

  1. Default or no-argument constructor.
  2. Parameterized constructor.

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 W3spoint
 */
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

Download this example.
Note: If no constructor is defined in the class then compiler automatically creates a default constructor at the time of compilation. 
Example:

/**
 * This program is used to show that compiler will automatically
 * creates the default constructor if not defined.
 * @author W3spoint
 */
public class ConstructorExample2 {
                int num;
                String str;               
 
                public static void main(String args[]){
                       //constructor call, compiler will automatically
                       //creates the default constructor
                       ConstructorExample2 obj1 = 
                                      new ConstructorExample2();
 
                       //print default values of object properties.
                       System.out.println("num = " + obj1.num);
                       System.out.println("str = " + o Dismiss bj1.str);
                }
}

Output:

num = 0
str = null

Download this example.

Parameterized constructor:

A constructor with one or more arguments is known as parameterized constructor.

Why parameterized constructor is used?

Parameterized constructor is used to provide values to the object properties. By use of parameterized constructor different objects can be initialize with different states.
Example:

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

Output:

Constructor called.
num = 10
str = W3spoint

Download this example.
Note: If a class contains parameterized constructor and default constructor is needed than default constructor has to be defined explicitly. In this case compiler will not provide default constructor. 
Example:

/**
 * This program is used to show that if a class contains
 * parameterized constructor and default constructor is needed
 * than default constructor has to be defined explicitly. In this
 * case compiler will not provide default constructor.
 * @author W3spoint
 */
public class ConstructorExample4 {
                int num;
                String str;
                ConstructorExample4(int n, String s){
                     System.out.println("Constructor called.");
                     num = n;
                     str = s;
                }
 
                public static void main(String args[]){
                    //constructor call
                    ConstructorExample4 obj1 = 
                          new ConstructorExample4(10, "w3spoint");
 
                    //error, because in this case default constructor
                    //will not be provided by compiler.
                    ConstructorExample4 obj2 = new ConstructorExample4();
 
                    //print values of object properties.
                    System.out.println("num = " + obj1.num);
                    System.out.println("str = " + obj1.str);
                }
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
The constructor ConstructorExample4() is undefined
at com.w3spoint.business.ConstructorExample4.main
(ConstructorExample4.java:23)

Download this example.

Constructor overloading in java.

The process of defining more than one constructor with different parameters in a class is known as constructor overloading. Parameters can differ in number, type or order.
Example:

/**
 * This program is used to show the use of constructor overloading.
 * @author W3spoint
 */
public class ConstructorExample5 {
       int num;
       boolean isStudent;
       String str;
 
 
       //One argument constructor
       ConstructorExample5(boolean boolean1){
       System.out.println("One argument constructor called.");
          isStudent = boolean1;
       }               
 
       //Two argument constructor
       ConstructorExample5(int n, String s){
        System.out.println("Two argument constructor called.");
        num = n;
        str = s;
       }    
 
       //Three argument constructor
       ConstructorExample5(boolean boolean1, int n, String s){
         System.out.println("Three argument constructor called.");
         isStudent = boolean1;
         num = n;
         str = s;
        }
       public static void main(String args[]){
         //one argument constructor call
         ConstructorExample5 obj1 = new ConstructorExample5(true);
 
         //print values of object properties.
         System.out.println("isStudent = " + obj1.isStudent);
         System.out.println("num = " + obj1.num);
         System.out.println("str = " + obj1.str); 
 
         //two argument constructor call
         ConstructorExample5 obj2 = 
               new ConstructorExample5(10, "W3spoint");
 
          //print values of object properties.
          System.out.println("isStudent = " + obj2.isStudent);
          System.out.println("num = " + obj2.num);
          System.out.println("str = " + obj2.str);
 
          //three argument constructor call
          ConstructorExample5 obj3 = new
          ConstructorExample5(false, 20, "W3spoint.com");
 
          //print values of object properties.
          System.out.println("isStudent = " + obj3.isStudent);
          System.out.println("num = " + obj3.num);
          System.out.println("str = " + obj3.str);
        }
}

Output:

isStudent = false
num = 20
str = W3spoint.com

Download this example.

Difference between constructor and method.

            Constructor               Method
  1. It has same name as of class.
  2. Invoked implicitly.
  3. Must not have any explicit return type.
  4. It is used to initialize the state of an object.
  1. It may or may not have same name as of class.
  2. Invoked explicitly.
  3. Must have a return type.
  4. It is used to show behavior of an object.

Note: An object can also perform any operation like any other method.

Does a constructor return any value?

Yes, a constructor implicitly returns the instance of the current class.

How to copy the values one object into another object using constructor?

Example:

/**
 * This program is used to copy the values one object
 * into another object using constructor.
 * @author W3spoint
 */
public class ConstructorExample6 {
       int num;
       String str;               
 
       ConstructorExample6(int n, String s){
            System.out.println("Constructor called.");
            num = n;
            str = s;
       }
 
        //This constructor will copy the value
        //of one object into another.
        ConstructorExample6(ConstructorExample6 obj){
            System.out.println("Constructor called
                                  for copying value.");
            num = obj.num;
            str = obj.str;
        }
 
        public static void main(String args[]){
           //parameterized constructor call
           ConstructorExample6 obj1 = new
                 ConstructorExample6(10, "W3spoint");
 
           //print values of object properties.  
           System.out.println("obj1 num = " + obj1.num);
           System.out.println("obj1 str = " + obj1.str);
           //Constructor call to copy the value
           //one object into other.
           ConstructorExample6 obj2 = new ConstructorExample6(obj1);
           //print values of object properties. 
           System.out.println("obj2 num = " + obj2.num);
           System.out.println("obj2 str = " + obj2.str);
       }
}

Output:

Constructor called for copying value.
obj2 num = 10
obj2 str = W3spoint

Download this example.
 

Java interview questions on constructor

 

Content Protection by DMCA.com
Please Share