Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Constructor in Java?
2.1.
Example
3.
Need of the Java Constructor
4.
Types of Constructors in Java
4.1.
Default Constructor
4.1.1.
Code
4.1.2.
Code
4.1.3.
Examples
4.2.
Java
4.3.
Parameterized Constructor
4.3.1.
Code
4.3.2.
Examples
4.4.
Java
4.5.
Java
4.6.
Copy Constructor
4.6.1.
Code
4.6.2.
Examples
4.7.
Java
4.8.
Java
5.
Characteristics of the Constructor
6.
Creating a Constructor
6.1.
Example
6.2.
Syntax of a Constructor
6.3.
Rules for creating a Constructor
6.4.
Examples of creating a Constructor
6.4.1.
Example:
6.5.
Java
6.5.1.
Output
7.
Constructor Overloading in Java
7.1.
How to Overload a Constructor?
7.2.
Examples of Constructor Overloading
7.2.1.
Simple Constructor Overloading
7.3.
Java
7.3.1.
Constructor Overloading with Inheritance
7.4.
Java
8.
Copy Constructor vs clone() Method
9.
Difference between Constructor and Method in Java
10.
Advantages of Copy Constructor
11.
Disadvantages of Copy Constructor
12.
Frequently Asked Questions
12.1.
What are the 3 types of Constructors?
12.2.
What is a Constructor in Java?
12.3.
Is constructor mandatory in Java?
12.4.
Why are constructors used?
13.
Conclusion
Last Updated: Mar 27, 2024
Easy

Constructor in Java

Author Riya Singh
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

In Java programming, constructors are like special tools that help us create and set up objects. They give each object its starting traits and play a vital role in getting things ready for action.

After reading this article, you will surely get a better understanding of Constructors in Java.

Also read, Swap Function in Java

What is Constructor in Java?

A Constructor is a unique method used to initialize the newly created object. It has the same name as that of the class. We can create a constructor with multiple parameters or no parameters. A class can have multiple constructors, and it totally depends on the programmer to make objects in different ways which will invoke the corresponding Constructor. We generally use Constructors to initialize an object's instance variables to a custom value or a default value. Let’s see an example to learn some implementation details of Constructor.

Example

class Working {
   public int variable1;
   public int variable2;
   public String mystring;

   public Working() {
       // initialize the variables with the default value
       this.variable1 = 0;
       this.variable2 = 0;
       this.mystring = "";
   }

   public Working(int first, int second) {
       this.variable1 = first;
       this.variable2 = second;
       this.mystring = "";
   }

   public Working(int first, int second, String cur) {
       this.variable1 = first;
       this.variable2 = second;
       this.mystring = cur;
   }

}


In the code above we have used three different Constructors for the empty objects, objects with two arguments and objects with three arguments. Depending on the scenario we can use any of these Constructors. 

 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Need of the Java Constructor

In the world of Java programming, constructors play a vital role by addressing the crucial need for initializing objects. Objects are the building blocks that let you create and manage various elements in your program. When an object is created, it needs to be properly set up and given initial values so that it's ready to be used. This is where constructors step in.

Constructors are like special methods within a class that are automatically called when you create an instance (object) of that class. They allow you to define how an object should be born and configured. By passing initial values as parameters, constructors ensure that an object starts off in a valid and usable state, reducing the chances of unpredictable behavior later on. Without constructors, you would need to set each property of an object manually after creation, which could lead to errors or inconsistencies.

Constructors simplify the process of object creation and initialization. They ensure that all the necessary attributes are properly set up, following the blueprint you've defined in your class. This promotes code consistency, reduces redundancy, and enhances code readability. In essence, constructors streamline the process of creating objects, making your Java programs more efficient, organized, and less error-prone.

Types of Constructors in Java

Types of Constructors in Java
  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

Default Constructor

A Default Constructor is a Constructor automatically generated by the compiler when a class has no explicitly defined constructor. It initializes the object’s instance variables by their default values. For example, if a class has instance variables of integer type, it initializes them with ‘0', If instance variables are of String type, it initializes them with “null”.

The code below shows how to create a default constructor.

Code

class Game {
   public int score;
   public String direction;
}

Since this class has no Constructor, the compiler will automatically make a default constructor which is equivalent to the constructor given below.

Code

public Game() {
   this.score = 0;
   this.direction = null;
}


Lets see some examples to learn the use-cases of the Default Constructor.

Examples

It can be used to create an object of a class without initialization any of its fields.

Code

class Registration {
   public int integer_field;
   public String string_field;
   // no constructor is present
}

 

class Solution {
   public static void main(String[] args) {
       // default constructor will be called
       Registration object = new Registration();
       System.out.println(object.integer_field);
       System.out.println(object.string_field);
   }
}

 

You can also try this code with Online Java Compiler

Run Code

 

Output

0
null


If a subclass does not have any Constructor that explicitly calls its superclass then the default Constructor of a superclass will automatically be called.

Code

  • Java

Java

class Ancestor {
  public String mystring;
  public boolean boolean_data;
}


class Children extends Ancestor {
  public int myvar1;
  public int myvar2;
}


class Solution {
  public static void main(String[] args) {
      Children object = new Children();
      // accessing instance variables of a superclass
      System.out.println(object.mystring);
      System.out.println(object.boolean_data);
  }
}


Output

null
false

 

Parameterized Constructor

A Parameterized Constructor is a Constructor which takes one or more parameters to initialize the instance variables for a particular object. It provides us flexibility to create the objects with the different values without calling the setter methods defined in a class. In a single class we can have multiple Constructors with different parameter lists, which leads to Constructor Overloading.

Let’s see an example to learn a bit more about the implementation of Parameterized Constructors.

Code

class Graph {
   public int nodes;
   public int edges;
   public String type;


   public Graph(int nodes, int vertices, String type) {
       this.nodes = nodes;
       this.edges = edges;
       this.type = type;
   }
}


This “Graph” class has one Parameterized Constructor which is initializing the instance variables of the class. 

Now, Let’s see some examples to understand the use of a Parameterized Constructor

Examples

Parameterized Constructors can be used to enforce encapsulation by making the instance variables private and using Constructor to set their values and access them by getter methods.

Code

  • Java

Java

class Store {
  private int bag_cost;
  private int shoe_cost;
  private String brand;


  // parameterized constructor
  public Store(int bag_cost, int shoe_cost, String brand) {
      this.bag_cost = bag_cost;
      this.shoe_cost = shoe_cost;
      this.brand = brand;
  }


  // getter methods
  public int get_bagcost() {
      return this.bag_cost;
  }
  public int get_shoecost() {
      return this.shoe_cost;
  }
  public String get_brand() {
      return this.brand;
  }


}


class Solution {
  public static void main(String[] args) {
      Store object = new Store(3000, 4500, "Levis");
      System.out.println(object.get_bagcost());
      System.out.println(object.get_shoecost());
      System.out.println(object.get_brand());
  }
}


Output

3000
4500
Levis


Parameterized Constructors are inherited by subclasses which allows subclasses to provide additional parameters to their Constructor.

Code

  • Java

Java

class Course {
  public int price;
  public int duration;
  public Course(int price, int duration) {
      this.price = price;
      this.duration = duration;
  }
}


class Frontend extends Course{
  public String framework;
  public int topics;
  public Frontend(int price, int duration, int topics, String framework) {
      // initialize instance variables of the superclass
      super(price, duration);
      // initialize its own fields
      this.framework = framework;
      this.topics = topics;
  }
}


class Solution {
  public static void main(String[] args) {
      Frontend object = new Frontend(2000, 60, 12, "Django");
      System.out.println(object.price);
      System.out.println(object.duration);
      System.out.println(object.framework);
      System.out.println(object.topics);


  }
}

 

Output

2000
60
Django
12

Copy Constructor

A Copy Constructor is a Constructor which initalizes the object with the copy of some other object of that same class. The new object has the same data members as the original object and it is a deep copy of the original object rather than a shallow copy. If we do any updates in the original object the changes should not be reflected in the copied object.

Let’s see how to create a Copy Constructor.

Code

class ConvexHull {
   public int xcordinate;
   public int ycordinate;
  
   public ConvexHull(ConvexHull other) {
       this.xcordinate = other.xcordinate;
       this.ycordinate = other.ycordinate;
   }
}

 


This “ConvexHull” class contains a Copy Constructor which initializes the instance variables of the current object with the instance variables of the object passed in the Constructor. 

Let’s see some examples to understand the use of a Copy Constructor

Examples

It creates a deep copy of an object which means if we update the copied object, it will not reflect any change in the original object.

Code

  • Java

Java

class Earbuds {
  public int wavelength;
  public double frequency;
  public Earbuds(int wavelength, double frequency) {
      this.wavelength = wavelength;
      this.frequency = frequency;
  }
  public Earbuds(Earbuds other) {
      this.wavelength = other.wavelength;
      this.frequency = other.frequency;
  }
}


class Solution {
  public static void main(String[] args) {
      Earbuds original = new Earbuds(20000, 0.5279);
      Earbuds copied = new Earbuds(original);
      // update the field of a copied object
      copied.wavelength = 1000;
      System.out.println(original.wavelength + " " + original.frequency);
      System.out.println(copied.wavelength + " " + copied.frequency);


  }
}


Output

20000 0.5279
1000 0.5279


We can create copies of an object while preserving the inheritance  hierarchy and properties of the original object

Code

  • Java

Java

class Tree {
  public int nodes;
  public int edges;
  public Tree(int nodes, int edges) {
      this.edges = edges;
      this.nodes = nodes;
  }
  public Tree(Tree other) {
      this.edges = other.edges;
      this.nodes = other.nodes;
  }
}


class Centroid extends Tree {
  public int center;
  public int depth;
  public Centroid(int nodes, int edges, int center, int depth) {
      super(nodes, edges);
      this.center = center;
      this.depth = depth;
  }
  public Centroid(Centroid other) {
      super(other);
      this.center = other.center;
      this.depth = other.depth;
  }
}


class Solution {
  public static void main(String[] args) {
      Centroid original = new Centroid(10, 9, 3, 3);
      Centroid copied = new Centroid(original);
      // update the copied object
      copied.center = 4;
      System.out.println(original.nodes + " " + original.edges + " " + original.center + " " + original.depth);
      System.out.println(copied.nodes + " " + copied.edges + " " +  copied.center + " " +  copied.depth);


  }
}


Output

10 9 3 3
10 9 4 3

 

Characteristics of the Constructor

  • The name of the class and its Constructor should be the same.
     
  • A Constructor can be overloaded which implies that a class can have multiple Constructors with a different number of parameters.
     
  • A Constructor can have access modifiers such as public, private and protected as that of a class.
     
  • A Constructor has no return type, its only purpose is to initialize the object.
     
  • We can also declare a Constructor as private. In that case we can only access it inside the class.
     
  • A child class can call a Constructor of its parent class but the vice-versa is invalid.
     
  • A default Constructor is automatically created if a class does not have any Constructor.
     
  • A Constructor can call another Constructor within the same class using the “this” keyword.

Creating a Constructor

To create a Constructor in Java, first define a class and then define a Constructor method with the same name as the class.

Example

class Myclass {
   // instance variables
   public int temp;
   public int random;
   // Create a Constructor
   public Myclass() {
       // no parameters
   }  
   // Constructor having two parameters
   public Myclass(int temp, int random) {
       this.temp = temp;
       this.random = random;
   }
}

Syntax of a Constructor

class Process {
   public String subtask1;
   public String subtask2;

   // creating a constructor having two parameters
   public Process(String subtask1, String subtask2) {
       this.subtask1 = subtask1;
       this.subtask2 = subtask2;
   }
}


The code above shows how to create a constructor. This “Process” class has a constructor having two parameters. We can initialize the class's instance variables with the values passed in the Constructor as parameters.

Rules for creating a Constructor

  • A Constructor name must be the same as its class name.
     
  • A Constructor must not have any return type.
     
  • If we define Constructor as static, it will not initialize the instance variables. So make sure to not use the “static” keyword while creating a Constructor.
     
  • If we define Constructor as abstract, it will not be called directly. So use of the “abstract” keyword is prohibited.
     
  • Constructors cannot be marked synchronized because the other threads cannot see the object being created until the thread creating it has finished it. 

Examples of creating a Constructor

Example:

  • Java

Java

class CN_Courses {
  // instance variables of the class
  public String course1;
  public int price1;
  public String course2;
  public int price2;

  // constructor with no parameters
  public CN_Courses() {
      this("default1", 0, "default2", 0);
  }

  // constructor with 2 parameters
  public CN_Courses(String course1, int price1) {
      this(course1, price1, "defaul2", 0);
  }

  // constructor with 4 parameters
  public CN_Courses(String course1, int price1, String course2, int price2) {
      this.course1 = course1;
      this.price1 = price1;
      this.course2 = course2;
      this.price2 = price2;
  }
}

class Solution {

  public static void print(CN_Courses myobject) {
      System.out.print(myobject.course1);
      System.out.print(" ");
      System.out.print(myobject.price1);
      System.out.print(" ");
      System.out.print(myobject.course2);
      System.out.print(" ");
      System.out.println(myobject.price2);
  }

  public static void main(String[] args) {
      // creating an object with all default parameters
      CN_Courses object1 = new CN_Courses();
      // creating an object with 2 default parameters
      CN_Courses object2 = new CN_Courses("frontend", 5000);
      // creating an object with no default parameter
      CN_Courses object3 = new CN_Courses("frontend", 5000, "backend", 6000);
      print(object1);
      print(object2);
      print(object3);
  }
}

Output

default1 0 default2 0
frontend 5000 defaul2 0
frontend 5000 backend 6000


Here the “CN_Courses”  class has three different Constructors, first with no parameters, second with the two parameters and finally the third with all the four parameters. In the Solution class we have a main function in which we have made three objects referring to the three different Constructors of the “CN_courses” class.  And finally we are printing all the instance variables of the objects.

Constructor Overloading in Java

It is a practice of defining more than one Constructor for a class with different parameter lists. It gives us flexibility to use any constructor depending on our use case. We can create objects in many ways because of the different variations of the Constructor. By providing multiple Constructors with different parameter lists, we can make our code more readable and easy to understand.

How to Overload a Constructor?

To overload a Constructor, we need to make multiple constructors with different parameter lists within the same class. The Java compiler determines which Constructor to call based on the arguments passed at the time of object creation. While overloading a Constructor, we can call one Constructor from the other using the “this” keyword.  

Examples of Constructor Overloading

Simple Constructor Overloading

Code

  • Java

Java

class Database {
  public String name1;
  public int age1;
  public String name2;
  public int age2;

  public Database() {
      this("default1", 0, "default", 0);
  }

  public Database(String name1, int age1) {
      this(name1, age1, "default", 0);
  }

  public Database(String name1, int age1, String name2, int age2) {
      this.name1 = name1;
      this.age1 = age1;
      this.name2 = name2;
      this.age2 = age2;
  }
}

class Solution {
  public static void print(Database data) {
      System.out.print(data.name1 + " ");
      System.out.print(data.age1 + " ");
      System.out.print(data.name2 + " ");
      System.out.print(data.age2 + " ");
      System.out.println();
  }

  public static void main(String[] args) {
      Database data1 = new Database();
      Database data2 = new Database("Mike", 25);
      Database data3 = new Database("Mike", 25, "John", 30);
      print(data1);
      print(data2);
      print(data3);
  }
}


Output

default1 0 default 0 
Mike 25 default 0 
Mike 25 John 30


This “Database” class has three different constructors based on the different parameter lists. In the main function of the Solution class we have defined three different objects to show how these three constructors are initializing the instance variables. 

Constructor Overloading with Inheritance

Code

  • Java

Java

class Parent {
  public int data1;
  public int data2;

  public Parent(int data1, int data2) {
      this.data1 = data1;
      this.data2 = data2;
  }
}

class Child extends Parent {
  public String message;

  public Child() {
      super(0, 0);
      this.message = null;
  }

  public Child(int data1, int data2, String message) {
      super(data1, data2);
      this.message = message;
  }
}

class Solution {
  public static void print(Child myobject) {
      System.out.print(myobject.data1 + " ");
      System.out.print(myobject.data2 + " ");
      System.out.print(myobject.message + " ");
      System.out.println();
  }
  public static void main(String[] args) {
     Child object1 = new Child();
     Child object2 = new Child(1, 2, "Hey there!!");
     print(object1);
     print(object2);
  }
}


Output

0 0 null 
1 2 Hey there!!


In this example, the “parent”  is a superclass and “child” is a subclass that extends it. The “parent” class has a single Constructor that takes data1 and data2 as parameters while the “child” class has two Constructors. The first “child” constructor takes no parameters and sets all the values to default and it passes these default values to the “parent” class using the “super” keyword. The second Constructor takes three parameters and initializes all the instance variables to these values by passing the data1 and data2 values to the superclass and sets the message value using “this” keyword.

Copy Constructor vs clone() Method

  • A Copy Constructor copies the values of an existing object into the new object, whereas the ‘clone’ method is used to create an object having the same states as the original object's.
     
  • A Copy Constructor is defined within the class and takes an object as a parameter whereas the ‘clone’ method is defined in the cloneable interface and implemented within the class.
     
  • The Copy Constructors are used to make the deep copies of an object such that changing the contents of an original object has no effect on the copied object whereas the ‘clone’ method is used to make shallow copies of an object in which the original object affects the instance variables of the copied object.
     
  • The Copy Constructors are generally preferred to make independent copies of an object whereas the ‘clone’ methods are preferred to make efficient copies of an object.
     
  • The Copy Constructors do not require any special interface whereas for the ‘clone’  method must be defined in the cloneable interface implemented by that class which explicitly overrides the ‘clone’ method.
     
  • The Copy Constructors can be used in the child class Constructors to copy the fields from the parent class, whereas the ‘clone’ method cannot be used in this way.

Difference between Constructor and Method in Java

Constructor Method
A Constructor is used to initialize the instance variables of an object.  A Method is used to create a specific task that can be called by the other parts of the program repeatedly.
It must have the same name as that of the class. A Method can have any name which follows the java naming convention.
It does not have any return type. It must have some return type like void, integer or String.
It calls the other Constructors of the same class using the “this” keyword. It calls the other methods of the class using the method name.
It can be called automatically when an object is created. It must be invoked manually using the method name.
It cannot have abstract, final or static modifiers. It can have abstract, final and static modifiers.
We cannot call Constructor explicitly. A Method must be called explicitly.
It cannot be overridden by the subclass. It can be overridden by the subclass.

Advantages of Copy Constructor

  • The Copy Constructor provides a way to initialize the values of a new object with the existing object, and it is very useful when we need deep copies of an object.
     
  • A Copy Constructor in the derived class can copy the values of the base class which allows us to make new objects which are polymorphic.
     
  • The use of Copy Constructor improves the performance of the program as it avoids the overhead of allocating and initializing the new memory.
     
  • It ensures that objects are properly initialized which helps when error occurs due to the improper initialization of an object.
     
  • The Copy Constructor allows us to change the values of the fields of newly created objects without changing the contents of an original object.

Disadvantages of Copy Constructor

  • The Copy Constructors are inefficient in inheritance, especially when the base class has a virtual function or involves multiple inheritances.
     
  • To copy an existing object, we need access to its internal state which violates the principle of encapsulation.
     
  • Copying an object is a computationally expensive operation for the complex objects and this leads to performance degradation in case of frequently copying an object.
     
  • The Copy Constructors can have issues with the private members of an object, where the Copy Constructor may not be able to access all the necessary fields to create an accurate copy of an object.
     

Also see, Hashcode Method in Java

Frequently Asked Questions

What are the 3 types of Constructors?

The 3 types of Constructors are Default Constructor (automatically generated by the compiler if no instructions is defined in the class), Parameterized Constructor (which takes one or more parameters to initialize the instance variables), Copy Constructor (which creates the new object by copying the values of an existing object).

What is a Constructor in Java?

A Constructor is a method that is used to create and initialize the objects of a class. It has the same name as that of class and it initializes the instance variables of the class.

Is constructor mandatory in Java?

Yes, constructors are mandatory in Java. Every class, if not explicitly defined, has a default constructor provided by Java. Constructors initialize object states and are crucial for proper object creation and initialization.

Why are constructors used?

Constructors are used to set initial values for object properties when an instance of a class is created. They ensure that objects start in a consistent state, avoiding unexpected behavior. Constructors also help enforce class invariants and enable efficient and organized object creation in Java programs.

Conclusion

In this article, we learned about what a Constructor is and the different types of constructors, along with their codes and outputs. Then we covered Constructor Overloading and in-depth analysis of Copy Constructors. Lastly, we discussed the differences between Constructor and Method, the advantages of Copy Constructor, and the disadvantages of Copy Constructor, along with some frequently asked questions. We hope this article has helped you enhance your knowledge of Constructors in Java.
Happy Learning Ninja!!

 

Live masterclass