Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Constructors in Java

  • Difficulty Level : Easy
  • Last Updated : 11 Nov, 2021

As the name suggests it is a terminology been used to construct something in our programs. So basically if we think deeper we always were declaring variables and later initializing them. Java being object-oriented language our goal is to bring code closer to real-world where we create objects now somebody is needed to look over the construction of these objects to get to how they are internally working.

Illustration: 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Animal gorilla  = new Animal() ;

Now here gorilla is an object and cant be set to 0 or null just unlikely int, char, float, etc so basically we need to initialize these objects as per requirements. This gives birth that there can be multiple types of constructors. 

Some of the geeks now must be wondering that they are unaware of the concept still they were successfully able to run programs. The answer is simple as there exists a default constructor having an empty body which is always called automatically if no constructor is written which was the reason for the successful initialization of objects at the backend. Now you must be wondering if this constructor is calling itself automatically then why there arises the need for multiple constructors. Refer to the above illustration for same where we can imagine many attributes are associated with it and it can not be initialized with 0 or null as it will make no sense hence we get to know why default constructor body is empty and still there arises the need for something to initialize attributes of objects in the java.



Now geek moving ahead you must be wondering about this keyword and with help of it we can achieve the goal but when the scalability of code increases it becomes so tedious to initialize attributes for objects at every place required arising duplicates lines in our code. So just likely we have learned to make a function when some repetitive work is being re-used in programs, same way here we have constructors which initialize and can call over objects just by writing inside some box which we will be seeing as a syntax where this block now is responsible for initialization of objects no matter how many and at what place in the code as the corresponding constructor will be automatically called just immediately after the object is initialized. Now let us technically deep dive into the concept.

How constructors are different from methods in Java? 

  • Constructors must have the same name as the class within which it is defined while it is not necessary for the method in java.
  • Constructors do not return any type while method(s) have the return type or void if does not return any value.
  • Constructors are called only once at the time of Object creation while method(s) can be called any number of time.

Now let us come up with the syntax for the constructor been invoked at the time of object or instance creation.

class Geek
{   
  .......

  // A Constructor
  new Geek() {}

  .......
}

// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek(); 

Remember: There are certain rules for writing constructor as follows:

  • Constructor(s) of a class must have the same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static and Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

So by far, we have learned constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.

Need of Constructor?

Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no. 
So constructors are used to assigning values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When is a Constructor called? 



Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. Now is the correct time to discuss types of the constructor, so primarily there are two types of constructors in java: 

  • No-argument constructor
  • Parameterized Constructor

Type 1: No-argument constructor

No-argument constructor: A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates default constructor(with no arguments) for the class. And if we write a constructor with arguments or no-arguments then the compiler does not create a default constructor. 

Default constructor provides the default values to the object like 0, null, etc. depending on the type.

Example:

Java




// Java Program to illustrate calling a
// no-argument constructor
import java.io.*;
 
class Geek
{
    int num;
    String name;
 
    // this would be invoked while an object
    // of that class is created.
    Geek()
    {
        System.out.println("Constructor called");
    }
}
 
class GFG
{
    public static void main (String[] args)
    {
        // this would invoke default constructor.
        Geek geek1 = new Geek();
 
        // Default constructor provides the default
        // values to the object like 0, null
        System.out.println(geek1.name);
        System.out.println(geek1.num);
    }
}
Output
Constructor called
null
0

Type 2: Parameterized Constructor

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.

Example:

Java




// Java Program to Illustrate Working of
// Parameterized Constructor
 
// Importing required inputoutput class
import java.io.*;
 
// Class 1
class Geek {
    // data members of the class.
    String name;
    int id;
 
    // Constructor would initialize data members
    // With the values of passed arguments while
    // Object of that class created
    Geek(String name, int id)
    {
        this.name = name;
        this.id = id;
    }
}
 
// Class 2
class GFG {
    // main driver method
    public static void main(String[] args)
    {
        // This would invoke the parameterized constructor.
        Geek geek1 = new Geek("adam", 1);
        System.out.println("GeekName :" + geek1.name
                           + " and GeekId :" + geek1.id);
    }
}
Output



GeekName :adam and GeekId :1

Remember: Does constructor return any value?

There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor.

Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. JustLike methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters. 

Example:

Java




// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;
 
class Geek
{
    // constructor with one argument
    Geek(String name)
    {
        System.out.println("Constructor with one " +
                      "argument - String : " + name);
    }
 
    // constructor with two arguments
    Geek(String name, int age)
    {
 
        System.out.println("Constructor with two arguments : " +
                " String and Integer : " + name + " "+ age);
 
    }
 
    // Constructor with one argument but with different
    // type than previous..
    Geek(long id)
    {
        System.out.println("Constructor with one argument : " +
                                            "Long : " + id);
    }
}
 
class GFG
{
    public static void main(String[] args)
    {
        // Creating the objects of the class named 'Geek'
        // by passing different arguments
 
        // Invoke the constructor with one argument of
        // type 'String'.
        Geek geek2 = new Geek("Shikhar");
 
        // Invoke the constructor with two arguments
        Geek geek3 = new Geek("Dharmesh", 26);
 
        // Invoke the constructor with one argument of
        // type 'Long'.
        Geek geek4 = new Geek(325614567);
    }
}
Output
Constructor with one argument - String : Shikhar
Constructor with two arguments :  String and Integer : Dharmesh 26
Constructor with one argument : Long : 325614567

In order to know to deep down into constructors there are two concepts been widely used as listed below: 

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!