Constructor (object-oriented programming)

Constructor in java is a special type of method that is used to initialize the object.Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Types

  • Parameterized constructors

  • Default constructors

  • Copy constructors

  • Conversion constructors

  • Move constructors

Parameterized_constructors

Constructors that can take arguments are termed as parameterized constructors. The number of arguments can be greater or equal to one(1). For example:

Default constructors

If the programmer does not supply a constructor for an instantiable class, most languages will provide a default constructor.

Copy constructors

define the actions performed by the compiler when copying class objects. A copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object). It is used to create a copy of an existing object of the same class. Even though both classes are the same, it counts as a conversion constructor.

Conversion constructors

Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly.

Move constructors

In C++, move constructors take a value reference to an object of the class, and are used to implement ownership transfer of the parameter object’s resources.

 




 

But In java there are only two types of constructors as shown belo:

download

Java

In Java, constructors differ from other methods in that:

  • Constructors never have an explicit return type.
  • Constructors cannot be directly invoked (the keyword “new” invokes them).
  • Constructors cannot be synchronized, final, abstract, native, or static.

Java constructors perform the following tasks in the following order:

  1. Initialize the class variables to default values. (byte, short, int, long, float, and double variables default to their respective zero values, booleans to false, chars to the null character (‘u0000’) and object references to null.)
  2. Call the default constructor of the superclass if no constructor is defined.
  3. Initialize member variables to the specified values.
  4. Executes the body of the constructor.

Java provides access to the superclass’s constructor through the super keyword.

Rules for creating java constructor

There are basically two rules defined for the constructor.

  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Above rules are also applicable for other languages like c++, c# etc.

public class Example
{
    // Definition of the constructor.
    public Example()
    {
        this(1);
    }

    // Overloading a constructor
    public Example(int input)
    {
        data = input; // This is an assignment
    }

    // Declaration of instance variable(s).
    private int data;
}


// Code somewhere else
// Instantiating an object with the above constructor
Example e = new Example(42);

A constructor taking zero number of arguments is called a “no-arguments” or “no-arg” constructor

 




Default Constructor

The default constructor is the no-argument constructor automatically generated unless you define another constructor. It initialises any uninitialised fields to their default values.
Lets see a simple example first: Refer the comments in the below program.

class NoteBook{
   /*This is my default constructor. A constructor does
    * not have a return type and it's name
    * should exactly same as class name
    */
   NoteBook(){
      System.out.println("Default constructor");
   }
   public void mymethod()
   {
      System.out.println("Void method of the class");
   }
   public static void main(String args[]){
	/* Creating object of class using default constructor
         * (new NoteBook()) so default constructor would be 
         * invoked 
         */
	NoteBook obj = new NoteBook();
	obj.mymethod();
   }
}

Output:


Default constructor
Void method of the class

As you can see in the above example that for creating the object of the class we have used the statement: NoteBook obj = new NoteBook();. Here NoteBook is class name, obj is object of class NoteBook, new keyword is for creating a new object and NoteBook() is the default constructor.

Note: If you try to create an object like this in above program: NoteBook obj = new NoteBook(12); then it would throw a compilation error because NoteBook(12) is referring to a constructor with single int argument, since we didn’t have a constructor with int argument in above example. The program would throw a compilation error in this case.

However the same does not apply for default constructor: Even if you do not define a default constructor in the class, the compiler does that for you implicitly.

Consider the below example: Here I didn’t declare any default constructor and I created the object of class using default constructor (new Example()) even then program ran fine without any issues. This shows that compiler creates a default empty constructor for a class if there is no constructor defined in it.

class Example{
   //I did not define any constructor here
   public void disp()
   {
      System.out.println("disp method of Example class");
   }
   public static void main(String args[]){
      Example obj2 = new Example();
      obj2.disp();
   }
}

Output:


disp method of Example class




Parameterized constructors

  1. Constructor Can Take Value , Value is Called as – “Argument“.
  2. Argument can be of any type i.e Integer,Character,Array or any Object.
  3. Constructor can take any number of Argument.
  4. See following example – How Parameterized Constructor Works ?

 

class Rectangle {
  int length;
  int breadth;

  Rectangle(int len,int bre)
  {
  length  = len;
  breadth = bre;
  }
}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle r1 = new Rectangle(20,10);

  System.out.println("Length of Rectangle : " + r1.length);
  System.out.println("Breadth of Rectangle : " + r1.breadth);

  }
}

Output :

Length of Rectangle  : 20
Breadth of Rectangle : 10

Explanation :

Carefully observe above program – You will found something like this –

Rectangle r1 = new Rectangle(20,10);
This is Parameterized Constructor taking argument.These arguments are used for any purpose inside Constructor Body.
Parameterized Constructor – Constructor Taking Argument

New Operator is used to Create Object.
We are passing Parameter to Constructor as 20,10.
These parameters are assigned to Instance Variables of the Class.
We can Write above statement like –

Rectangle(int length,int breadth)
  {
  length  = length;
  breadth = breadth;
  }
OR

Rectangle(int length,int breadth)
  {
  this.length  = length;
  this.breadth = breadth;
  }

But if we use Parameter name same as Instance variable then compiler will recognize instance variable and Parameter but user or programmer may confuse. Thus we have used “this keyword” to specify that “Variable is Instance Variable of Object – r1“.

 

Constructor Overloading

Constructor overloading in java allows to have more than one constructor inside one Class. in last article we have discussed about method overloading and overriding and constructor overloading is not much different than method overloading. Just like in case of method overloading you have multiple methods with same name but different signature, in Constructor overloading you have multiple constructor with different signature with only difference that Constructor doesn’t have return type in Java. Those constructor will be called as overloaded constructor . Overloading is also another form of polymorphism in Java which allows to have multiple constructor with different name in one Class in java.

 

Some points we need to remember related to Constructor Overloading

1. Constructor overloading is similar to method overloading in Java.

2. You can call overloaded constructor by using this() keyword in Java.

3. overloaded constructor must be called from another constructor only.

4. make sure you add no argument default constructor because once compiler will not add if you have added any constructor in Java.

5. if an overloaded constructor called , it must be first statement of constructor in java.

6. Its best practice to have one primary constructor and let overloaded constructor calls that. this way
your initialization code will be centralized and easier to test and maintain.

That’s all on Constructor overloading in java. Biggest advantage of Constructor overloading is flexibility which allows you to create object in different way and classic examples are various Collection classes. Though you should remember that once you add a constructor, compiler will not add default no argument constructor.

Example:

package com.myjava.constructors;
 
public class MyOverloading {
     
    public MyOverloading(){
        System.out.println("Inside default constructor");
    }
    public MyOverloading(int i){
        System.out.println("Inside single parameter constructor with int value");
    }
    public MyOverloading(String str){
        System.out.println("Inside single parameter constructor with String object");
    }
    public MyOverloading(int i, int j){
        System.out.println("Inside double parameter constructor");
    }
     
    public static void main(String a[]){
        MyOverloading mco = new MyOverloading();
        MyOverloading spmco = new MyOverloading(10);
        MyOverloading dpmco = new MyOverloading(10,20);
    MyOverloading dpmco = new MyOverloading("java2novice");
    }
}

Output

Inside default constructor 
Inside single parameter constructor with int value 
Inside double parameter constructor 
Inside single parameter constructor with String object

If you have any doubt in constructor freely ask to us we are happy to help you