Constructor in Java with Example

Free Java courses with 37 real-time projects - Learn Java

Constructors… The name itself is so creative in nature, isn’t it?

Well, constructors are basically the mould to objects. It gives the object its shape and meaning.

Example time!

If you ever visit a factory where some hot metal is being pushed through a mould, you will see exactly why I compared constructors with moulds in the first place.

The metal, molten, fuming hot, has a very unique property, it is a liquid. It can change its shape to any possible shape you can imagine. The mould gives it the shape and identity.

Constructors in Java do the same.

What is Constructor in Java?

A constructor in Java is simply a bundle of statements that are particularly useful for initializing the object with default values.

For example, when you are declaring an object you may want the class variables to start off with some default value, right? Well, constructors are the ideal tool for that.

You can also use the constructors to allow class variables to take up specific user-defined values during object definition.

This simply means that the user can specify explicit values to the class members during each object creation. These are parameterized constructors. We will be reading about them shortly.

A constructor always has the exact same name as that of a class. When you create a new object of a class, the compiler calls the constructor of the class.

If no constructor is present in the class explicitly, then the compiler declares a default compiler for itself and initializes the class variables automatically. This constructor is default constructor in Java.

A constructor is useful for initializing the properties of the objects. As soon as the new() method gets executed the constructor for the class gets called.

Syntax

class <class_name>
{
int class_var1,class_var2;

//the constructor 

<class_name>()
{
    //this is the constructor 
    //This is where you initialize the class variables. 
    class_var1=0;
    class_var2=2;
}
}

Note that even if we do not explicitly mention a constructor, the compiler will add a constructor by default and assign all variables with their default values.

These are the basics of constructors in Java.

There are certain rules that we should keep in mind when writing constructors.

  • The constructor should have the same name as that of the class.
  • A constructor can not be static, final or synchronized.
  • You can use access modifiers to limit access to the constructor.

Need of Constructors in Java

Constructors are generally useful for writing user-specific values to the instance variables.

These can also be used when the programmer needs to set explicit or default values to the member variables of the class.

Types of Constructors in Java

Constructors in Java

There are a few types of constructors in Java. Let us get to know them one by one.

1. Java Default Constructor

As we already talked about before, if the programmer does not explicitly declare a constructor then the compiler does that implicitly.

It assigns default values to objects and the variables based on the datatype. Well enough talk. Let us get our hands dirty!

package com.dataflair.constructorsinjava
public class ConstructorTypes
{
    int defaultvalueint;
    String defaultString;
    public static void main(String[] args) {
        System.out.println("This is the default constructor at work. ");

        ConstructorTypes object = new ConstructorTypes();//We called the default constructor here
        System.out.println("The default values of int data type is "+object.defaultvalueint);
        System.out.println("The default values of the String data type is "+object.defaultString);

        
    }
}

Output:

This is the default constructor at work.
The default values of int data type is 0
The default values of the String data type is null

2. Java No Parameter Constructor

A no parameter constructor is similar to what the compiler creates when we do not explicitly declare a constructor. This is also a default constructor.

Let us see an example of Java Constructor with no parameter:

package com.dataflair.constructorsinjava
public class ConstructorTypes
{
    int defaultvalueint;
    String defaultString;
    ConstructorTypes()
    {
        System.out.println("This is the default constructor... It doesn’t do much except assigning default values to class variables.");
    }
    public static void main(String[] args) {

        ConstructorTypes object = new ConstructorTypes();//We called the default constructor here
        System.out.println("The default values of int data type is "+object.defaultvalueint);
        System.out.println("The default values of the String data type is "+object.defaultString);


    }
}

Output:

This is the default constructor… It doesn’t do much except assigning default values to class variables.
The default values of int data type is 0
The default values of the String data type is null

3. Java Parameterized Constructor

The real power of constructors can be leveraged by using parameterized constructors.

You can explicitly set the values of the class variables while declaring objects with the help of parameterized constructors.

package com.dataflair.constructorsinjava
public class ConstructorTypes
{
    int defaultvalueint;
    String defaultString;
    ConstructorTypes(int val, String value)
    {
        System.out.println("This is the parameterized constructor");
        defaultString=value;
        defaultvalueint=val;
    }
    public static void main(String[] args) {

        ConstructorTypes object = new ConstructorTypes(52,"DataFlair");//We called the default constructor here
        System.out.println("The default values of int data type is "+object.defaultvalueint);
        System.out.println("The default values of the String data type is "+object.defaultString);


    }
}

Output:

This is the parameterized constructor
The default values of int data type is 52
The default values of the String data type is DataFlair

A point to note would be that constructors cannot return values. However, you can return the instance of the current class with the help of constructors.

Constructor Chaining in Java

As the name suggests, the chaining of constructors is simply calling a different constructor each time when the control shifts inside a particular constructor.

Simply, it is the linking of multiple constructors in a class.

You can achieve constructor chaining with the help of “this” keyword.

But why is this concept in practice? I mean, wouldn’t it be easy to declare the constructors and call them individually anyway?

Well yes, but constructor chaining particularly proves to be helpful when you need to do multiple tasks in a single constructor.

The consecutive calls to the constructors help in defining each and every value.

One important point to note is that the this() call should be before any other statement in the constructor. If not then the compiler returns an error.

It is time for another example again!

Java program to illustrate Java constructor chaining:

package com.dataflair.constructorsinjava;
public class ConstructorChaining {

    ConstructorChaining()
    {
        this(100);
        //call made to constructor with one parameter of type int
        System.out.println("This is the default constructor ");

    }
    ConstructorChaining(int x)
    {
        this(x,"DataFlair");
        //constructor call made with two parameters. 
        System.out.println("This is a parameterized constructor");


    }
    ConstructorChaining(int x, String s)
    {
        System.out.println(s+" "+x);
        System.out.println("This is the final constructor call. ");
    }
        public static void main(String[] args) {

            ConstructorChaining object = new ConstructorChaining();
            
            
        }
}

Output:

DataFlair 100
This is the final constructor call.
This is a parameterized constructor
This is the default constructor

Super Method in Java

When the super method gets executed, the control shifts to the constructor of the parent class.

During the initialization of a child class object, the compiler implicitly calls the superclass constructor.

Let us see with an example

Java program to illustrate the use of super() method:

package com.dataflair.constructorsinjava;
class A
{
    A()
    {
        System.out.println("This is the constructor of class A");
    }

}
class B extends A
{
    B()
    {
        super();
        System.out.println("This is the constructor of class B");
    }
}
public class SuperConstructor {
    public static void main(String[] args) {
        
        B ob = new B();

    }
}

Output:

This is the constructor of class A
This is the constructor of class B

Java Constructor Overloading

Similar to function overloading, constructor overloading involves the process of using the same name(which is evident because constructors and the classes share the same name) having different parameters.

The compiler chooses the constructor based on the datatypes and the number of the parameters. This process is similar to function overloading.

Java program to illustrate the use of Constructor Overloading:

package com.dataflair.constructorsinjava;
class A
{
    A()
    {
        System.out.println("This is the default constructor");

    }
    A(int a)
    {
        System.out.println("This constructor consists of a single parameter of value "+a);
    }
    A(int a, String s)
    {
        System.out.println("This constructor consists of two parameters of values "+a+", "+s);
    }
}

public class ConstructorOverloading {
    public static void main(String[] args) {
     
    A obj=new A();
    A obj1=new A(5,"DataFlair");   
    }
    

}

Output:

This is the default constructor
This constructor consists of two parameters of values 5, DataFlair

Copy Constructor in Java

Copy constructors are particularly useful for copying the values of an object into a different object.

Many a time, some objects need to have the same instance values. This is where copy constructors come in.

Java program to illustrate the use of Copy Constructors:

package com.dataflair.constructorsinjava;
public class CopyConstructor {
    String s;
    CopyConstructor(String string)
    {   
        this.s=string;

    }
    CopyConstructor(CopyConstructor object)
    {
        this.s=object.s;
    }
    public void valuesdisplay()
    {
        System.out.println("The object has the values-> "+s);
    }
    public static void main(String[] args) {

        CopyConstructor object=new CopyConstructor("DataFlair");
        CopyConstructor copyobject=new CopyConstructor(object);
        object.valuesdisplay();
        copyobject.valuesdisplay();

        
    }
    
}

Output:

The object has the values-> DataFlair
The object has the values-> DataFlair

As you can see the “copy object” has the same values of instance variables as the primary object. This is possible due to copy constructors.

Difference Between Java Constructors and Java Methods

Constructors in JavaMethods in Java
Constructors must always have the same name as that of the class.The methods can have any name the programmer wants. However, it should not be an identifier or a reserved word. 
Constructors cannot return a value. It can only return references. Methods can return values. 
The JVM invokes constructors implicitly whenever you create a new object. You can call methods explicitly. 
If no constructor is present, the JVM implicitly creates a default constructor. If a method is not present, the JVM does not create default methods implicitly. 
Constructors are particularly useful for initializing an object. Methods are useful when you need to add specific functionality to an object. 
A single constructor is non-inheritable by child classes. Methods are inheritable by child classes. 
A single class can have more than one constructor. But no two constructors can have the same parameters. A single class can have more than one method. But no two methods can have the same name and the same parameters. 
A constructor cannot be final, static or synchronizable. Methods can be static, final or synchronized. 

Points to Remember for Constructors in Java

  1. Firstly, The constructors should have the same name as that of the class.
  2. Constructors cannot return anything except the reference of the object.
  3. You can declare a constructor as private protected default or public.
  4. If there is no explicit mention of a constructor inside a class, the compiler will add a default constructor implicitly.
  5. If you are using this() or super() care should be taken that these statements should be the first lines of code in the constructor scope.
  6. You can overload a constructor but you cannot override it.
  7. You cannot explicitly inherit a constructor.
  8. One cannot instantiate abstract classes. But they do have constructors. These constructors will be invoked when the class which implements the abstract class gets instantiated.
  9. The compiler would not insert a default constructor in the child class if the superclass doesn’t have a default constructor.
    this() allows you to chain constructors together.
  10. The main difference between methods and constructors is that methods can return values and have a different name. But constructors have the same name as the class itself and can only return references. They cannot return values.
  11. Lastly, There are no constructors in interfaces.

Quiz on Constructor in Java

Summary

In this article, we learned about the various aspects of constructors in java, its types and how to use them to our advantage.

Constructors may seem like an easy topic but interviewers manage to ask very tricky questions based on it. So it is extremely important to have a concrete knowledge of constructors during interviews.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

3 Responses

  1. abhi says:

    The English used in the tutorial is quite confusing and is not easy to understand. You guys should look to simplify the use of English, for example, this line

    “Default constructor in Java gives the default esteems to the protest like 0, invalid and so on relying upon the sort.”

    is not easy for a newbie(both for Java and English) to understand.

  2. Koki says:

    Really Awesome explanations for begineers

Leave a Reply

Your email address will not be published. Required fields are marked *