Constructors in Java

1

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.

When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.

Constructor is invoked at the time of object or instance creation. For Example:

class Geek
{   
  .......

  // A Constructor
  new Geek() {}

  .......
}

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

Rules for writing Constructor:

  • Constructor(s) of a class must has 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.

Types of constructor

There are two type of constructor in Java:

  1. No-argument constructor: A constructor that has no parameter is known as default constructor. If we don’t define a constructor in a class, then compiler creates default constructor(with no arguments) for the class. And if we write a constructor with arguments or no-argument then compiler does not create default constructor.
    Default constructor provides the default values to the object like 0, null etc. depending on the type.

    // Java Program to illustrate calling a
    // no-argument constructor
    import java.io.*;
    
    class Geek
    {
        int num;
        String name;
    
        // this would be invoked while object
        // of that class 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
    
  2. Parameterized Constructor: A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with your own values, then use parameterized constructor.

    // Java Program to illustrate calling of
    // parameterized constructor.
    import java.io.*;
    
    class Geek
    {
        // data members of the class.
        String name;
        int id;
    
        // contructor would initialized 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 GFG
    {
        public static void main (String[] args)
        {
            // this would invoke parameterized constructor.
            Geek geek1 = new Geek("adam", 1);
            System.out.println("GeekName :" + geek1.name +
                               " and GeekId :" + geek1.id);
        }
    }
    

    Output:

    GeekName :adam and GeekId :1
    

Does constructor return any value?

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

Constructor Overloading

Like 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.

// 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.print("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

How constructors are different from methods in Java?

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

Related Articles:

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 11 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.