Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Constructors In Java programming 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. It is called automatically when an object of a class is created and is essential for setting initial values for the object’s attributes. Constructors help in defining the state of an object when it is instantiated.
After reading this article, you will surely get a better understanding of Constructors 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 of Java Constructor
Java
Java
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; }
}
You can also try this code with Online Java Compiler
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.
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
There are Three types of Constructors in Java:-
Default Constructor
Parameterized Constructor
Copy Constructor
1. Default Constructor
A Default Constructor in Java 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.
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.
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 Implementation
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);
}
}
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 Implementation
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); } }
You can also try this code with Online Java Compiler
A Parameterized Constructor in Java 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.
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 Implementation
Java
Java
class Store { private int bag_cost; private int shoe_cost; private String 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()); } }
You can also try this code with Online Java Compiler
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);
} }
You can also try this code with Online Java Compiler
A Copy Constructor in Java 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.
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 Implementation
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);
} }
You can also try this code with Online Java Compiler
We can create copies of an object while preserving the inheritance hierarchy and properties of the original object
Code Implementation
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; } }
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.
How to Create a Constructor in Java?
To create a Constructor in Java, first define a class and then define a Constructor method with the same name as the class.
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.
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.
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; } }
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); } }
You can also try this code with Online Java Compiler
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.
What is Constructor Overloading in Java?
Constructor Overloading in Java 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.
Examples of Java Constructor Overloading
Example 1 - 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; } }
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.
Example 2 - 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); } }
You can also try this code with Online Java Compiler
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.
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.
Constructor Chaining in Java
Constructor chaining in Java refers to the process of calling one constructor from another constructor in the same or a superclass. This can be done using this() to call another constructor within the same class, or super() to invoke a constructor of the superclass.
Code Implementation:
Java
Java
class Person { Person() { System.out.println("Person constructor called"); }
Person constructor called
Person constructor with name: John
Java Super Constructor
In Java, the super() keyword is used to call the constructor of a superclass. This is especially useful in inheritance when a subclass needs to invoke a constructor of its parent class. The super() call must be the first statement in a subclass constructor and ensures that the parent class is properly initialized before the subclass executes its own logic.
Code Implementation:
Java
Java
class Animal { Animal() { System.out.println("Animal constructor called"); } }
class Dog extends Animal { Dog() { super(); // Calling the superclass constructor System.out.println("Dog constructor called"); } }
public class Main { public static void main(String[] args) { Dog d = new Dog(); } }
You can also try this code with Online Java Compiler
In this example, the Dog constructor invokes the Animal constructor using super(), ensuring the base class is initialized first.
Frequently Asked Questions
Can a Java constructor be private?
Yes, a Java constructor can be private. This is typically done to prevent object creation from outside the class, often in cases like Singleton design patterns where a single instance of a class is required.
What happens if a class has no constructor?
If a class does not explicitly define a constructor, Java automatically provides a default no-argument constructor. This constructor initializes the object with default values, such as null for objects and 0 for numeric types.
What is a no-argument constructor?
A no-argument constructor is a constructor that does not take any parameters. It initializes an object with default values and is automatically provided by Java if no other constructors are defined in the class.
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.
Conclusion
In conclusion, constructors are a fundamental concept in Java, essential for initializing objects and ensuring that they are properly set up before use. Whether it's a no-argument constructor, parameterized constructor, or constructor chaining, understanding how constructors work is vital for writing efficient and organized object-oriented code.