Java Constructor

Constructor

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

Characteristics of the constructor

  1. A constructor has the same name as its class.
  2. Constructor is invoked at the time of object creation and used to initialize the state of an object.
  3. A constructor 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 a default or no-argument constructor. If no constructor is defined in the class then the compiler automatically creates a default constructor at the time of compilation.

Syntax

ClassName(){

       //Block of code (Optional)

}

Why default constructor is used?

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

Example

package com.w3schools;

public class ConstructorTest {
    int num;
    String str;

    ConstructorTest() {
        System.out.println("Constructor called.");
    }

    public static void main(String args[]) {
        ConstructorTest obj = new ConstructorTest();

        System.out.println("num = " + obj.num);
        System.out.println("str = " + obj.str);
    }
}

Output

Constructor called.
num = 0
str = null

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

Example

package com.w3schools;

public class ConstructorTest {
    int num;
    String str;

    public static void main(String args[]) {
        ConstructorTest obj = new ConstructorTest();

        System.out.println("num = " + obj.num);
        System.out.println("str = " + obj.str);
    }
}

Output

num = 0
str = null

Parameterized constructor:

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

Why parameterized constructor is used?

It is used to provide values to the object properties. By use of a parameterized constructor, different objects can be initialized with different states.

Example

package com.w3schools;

public class ConstructorTest {
    int num;
    String str;

    ConstructorTest(int n, String s) {
        System.out.println("Constructor called.");
        num = n;
        str = s;
    }

    public static void main(String args[]) {
        ConstructorTest obj = new ConstructorTest(10, "W3schools360.com");

        System.out.println("num = " + obj.num);
        System.out.println("str = " + obj.str);
    }
}

Output

Constructor called.
num = 10
str = W3schools360.com

Note: If a class contains a parameterized constructor and a default constructor is needed then the default constructor has to be defined explicitly. In this case, the compiler will not provide a default constructor. 

Example

package com.w3schools;

public class ConstructorTest {
    int num;
    String str;

    ConstructorTest(int n, String s) {
        System.out.println("Constructor called.");
        num = n;
        str = s;
    }

    public static void main(String args[]) {
        ConstructorTest obj1 = new ConstructorTest(10, "wschools360.com");

        // There will be an error here
        // Because there is no default constructor available
        ConstructorTest obj2 = new ConstructorTest();

        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 ConstructorTest() is undefined

    at com.w3schools.ConstructorTest.main(ConstructorTest.java:18)

Constructor overloading in Java.

A way 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

package com.w3schools;

public class ConstructorTest {
       int num;
       boolean isStudent;
       String str;
               

       //One argument constructor
       ConstructorTest(boolean boolean1){
       System.out.println("One argument constructor called.");
          isStudent = boolean1;
       }               

       //Two argument constructor
       ConstructorTest(int n, String s){
        System.out.println("Two argument constructor called.");
        num = n;
        str = s;
       }    

       //Three argument constructor
       ConstructorTest(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
    	  ConstructorTest obj1 = new ConstructorTest(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
         ConstructorTest obj2 = new ConstructorTest(10, "W3schools360");

          //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
          ConstructorTest obj3 = new ConstructorTest(false, 20, "W3schools360");

          //Print values of object properties.
          System.out.println("isStudent = " + obj3.isStudent);
          System.out.println("num = " + obj3.num);
          System.out.println("str = " + obj3.str);
        }
}

Output

One argument constructor called.
isStudent = true
num = 0
str = null
Two argument constructor called.
isStudent = false
num = 10
str = W3schools360
Three argument constructor called.
isStudent = false
num = 20
str = W3schools360

Constructor Vs Method

            Constructor               Method
  1. The Constructor must have the same name as its class.
  2. Constructor invoked implicitly.
  3. Must not have any explicit return type.
  4. A constructor provides the feature to initialize the state of an object.
  1. The method may or may not have the same name as of class.
  2. Method invoked explicitly.
  3. Must have a return type.
  4. A method is used to show the behavior of an object.

 

Does a constructor return any value?

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

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

package com.w3schools;

public class ConstructorTest {
    int num;
    String str;

    ConstructorTest(int n, String s) {
        System.out.println("Constructor called.");
        num = n;
        str = s;
    }

    // This constructor will copy the value of one object into another.
    ConstructorTest(ConstructorTest obj) {
        System.out.println("Constructor called for copying value.");
        num = obj.num;
        str = obj.str;
    }

    public static void main(String args[]) {
        // Parameterized constructor call
        ConstructorTest obj1 = new ConstructorTest(10, "W3schools360");

        // 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 from one object into another.
        ConstructorTest obj2 = new ConstructorTest(obj1);

        // Print values of object properties.
        System.out.println("obj2 num = " + obj2.num);
        System.out.println("obj2 str = " + obj2.str);
    }
}

Output

Constructor called.
obj1 num = 10
obj1 str = W3schools360
Constructor called for copying value.
obj2 num = 10
obj2 str = W3schools360

 

Please follow and like us:
Content Protection by DMCA.com