Java Constructor: Here’s Everything You Need to Know

Posted in /  

Java Constructor: Here’s Everything You Need to Know

Ramya Shankar
Last updated on June 29, 2022

    Java is a high-level object-oriented programming language used for developing desktop, mobile, and web applications. It was developed by James Goslings at Sun Microsystems in 1995. Today, it is widely used as a server-side scripting language for web development projects. Since Java is an object-oriented programming language, it uses a constructor to initialize an object of a class. This article is intended to familiarize you with constructors in Java. Also, we will discuss everything about the Java Constructor, such as how to create it, its types, and how to use it (with examples). So, let us get started!

    What is a Java Constructor?

    In Java, a constructor is a special method or a block of code that is invoked when an object of a class is instantiated. When we call a Java constructor, the object is allocated with the memory. The sole purpose of a constructor is to initialize the newly created object. When we create an object of a particular class using the new() keyword, at least one constructor is called to assign initial values to the data members of that class. If we do not define any constructor in a Java class, the Java compiler provides a default constructor. Once we define our own constructor, the Java compiler will no longer use the default one.

    Rules for Creating a Constructor

    There are certain rules to follow while creating a constructor in Java that are as follows:

    • The name of the constructor and the class should be the same.
    • A constructor should not have an explicit return type.
    • A constructor cannot be static, final, synchronized, and abstract.

    Nonetheless, we can use access modifiers while declaring a constructor. Therefore, constructors in Java can be public, private, or protected.

    Syntax for Creating Java Constructor

    The following is the syntax for creating a constructor in Java:

    class ClassName {
    ClassName() {
    
    }
    }

    Types of Constructors in Java

    There are two different kinds of constructors in Java, namely no-arg or default constructor and parameterized constructor. Let us discuss each of these constructors with examples below.

    1. Default or No-arg Constructor

    As its name suggests, no-arg or default constructors do not have any arguments or parameters. The Java compiler creates a default constructor if no constructor is defined. A default constructor assigns default values to an object, i.e., 0 or null, depending upon its data type. Syntax:

    ClassName() {}

    Example 1:

    import java.io.*;
    public class TeckGeekBuzz
    {
    TeckGeekBuzz()
    {
    System.out.println("Welcome to TeckGeekBuzz!");
    }
    public static void main(String args[]){
    TeckGeekBuzz tbg=new TeckGeekBuzz();
    }
    }

    Output:

    Welcome to TechGeekBuzz!

    Now, let us write a Java program for creating a default constructor that displays default values. Example 2:

    import java.io.*;
    public class TechGeekBuzz
    {
    int num;
    String name;
    
    TechGeekBuzz()
    {
    System.out.println("Welcome to TechGeekBuzz!");
    }
    public static void main (String[] args)
    {
    TechGeekBuzz tgb = new TechGeekBuzz();
    System.out.println(tgb.name);
    System.out.println(tgb.num);
    }
    }

    Output:

    Welcome to TechGeekBuzz!
    null
    0

    In the above example, the constructor ‘TeckGeekBuzz’ assigns a default value to the data variable ‘num’, i.e., 0, since it is of the integer data type. On the other hand, it assigns the data variable ‘name’ as null since it is of the string data type.

    2. Parameterized Constructor

    A constructor that has one or more parameters is called a parameterized constructor. This type of constructor is used to initialize the fields of a class with the desired values. With a parameterized constructor, we can provide different or same values to different Java objects. Syntax:

    ClassName(data type X, data type Y, data type Z, ...);

    Here, X, Y, Z, are parameters. Example:

    import java.io.*;
    public class TechGeek
    {
    int id;
    String name;
    TechGeek(int i, String n)
    {
    id = i;
    name = n;
    }
    void display()
    {
    System.out.println(id+" "+name);
    }
    public static void main(String args[])
    {
    TechGeek tgb1 = new TechGeek(01, "John");
    TechGeek tgb2 = new TechGeek(02, "Sam");
    tgb1.display();
    tgb2.display();
    }
    }

    Output:

    01 John
    02 Sam

    3. Constructor Overloading

    Like we overload methods in Java, we can also overload constructors but without return type. Constructor overloading is a technique of having one or more constructors with the same name but with a different parameter list, where each constructor performs a different task. The Java compiler differentiates these constructors depending on the number of parameters in the list and their data types . Example:

    import java.io.*;
    public class TechGeek1
    {
    TechGeek1(String name)
    {
    System.out.println(name);
    }
    TechGeek1(String name, int age)
    {
    System.out.println(name+" "+age);
    }
    TechGeek1(long id)
    {
    System.out.println(id);
    }
    
    public static void main(String args[])
    {
    TechGeek1 tgb1 = new TechGeek1("John");
    TechGeek1 tgb2 = new TechGeek1("Sam", 25);
    TechGeek1 tgb3 = new TechGeek1(234566778);
    }
    }

    Output:

    John
    Sam 25
    234566778

    4. Copy Constructor

    A copy constructor in Java is a constructor that creates an object using the existing object of the same class. In Java, the copy constructor is not created by default, like in C++. We can use the copy constructor if we need to:

    • Create a copy of an object having several fields.
    • Create a deep copy of the existing objects.
    • Avoid the use of the Object.clone() method.

    There are three ways to copy the values of one object to another that are listed below:

    1. Using a constructor.
    2. Assigning values of one constructor to another.
    3. Using the clone() of the Object class.

    Copy Constructor using Java Constructor

    Let us write a program for copying the values of one object to another using a Java constructor. Example:

    import java.io.*;
    public class TechGeek2
    {
    int id;
    String name;
    TechGeek2(String n, int i)
    {
    name = n;
    id = i;
    }
    TechGeek2(TechGeek2 s)
    {
    name = s.name;
    id = s.id;
    }
    void display()
    {
    System.out.println(name+" "+id);
    }
    public static void main(String args[])
    {
    TechGeek2 tgb = new TechGeek2("John", 38);
    TechGeek2 tgb1 = new TechGeek2(tgb);
    tgb.display();
    tgb1.display();
    }
    }
    

    Output:

    John 38
    John 38

    Copy Constructor without using Java Constructor

    We have seen how to use a constructor to copy the values of one object to another. Let us now write the Java program to copy the values of an object by simply assigning its values to another object. Example:

    import java.io.*;
    public class TechGeek3
    {
    int id;
    String name;
    TechGeek3(String n, int i)
    {
    name = n;
    id = i;
    }
    TechGeek3()
    {
    }
    void display()
    {
    System.out.println(name+" "+id);
    }
    public static void main(String args[])
    {
    TechGeek3 tgb = new TechGeek3("Henry", 45);
    TechGeek3 tgb1 = new TechGeek3();
    tgb1.name = tgb.name;
    tgb1.id = tgb.id;
    tgb.display();
    tgb1.display();
    }
    }
    

    Output:

    Henry 45
    Henry 45

    Copy Constructor vs Clone() Method

    The Clone() method and copy constructor allows us to create the exact copy of an existing object. However, the copy constructor is far better than the Clone() method because of the following reasons:

    • The Clone() method requires us to import Clonable present in java.lang package. Also, this method may throw the exception named CloneNotSupportException . Therefore, we have to handle this exception in our Java program.
    • We can assign values to the final fields in the copy constructor, whereas we cannot do it in the Clone() method.
    • The copy constructor does not require typecasting, while the object returned by the Clone() method must be typecast .

    To Sum it Up

    Learning how a Java constructor works is quite important for every Java developer. In general, a Java constructor is a particular block of code that initializes an object of a Java class and is called when the object is created. In this article, we have explained the different types of constructors in Java with appropriate examples. Also, we have covered two other important concepts, namely Constructor overloading and Copy Constructor in Java.

    People are also reading:

    Leave a Comment on this Post

    0 Comments