In any object-oriented language, programmers can define classes and create objects. In these scenarios, a class member needs a way to be initialized. A constructor is a special method pertaining to a class which can initialize the members of a class with values you desire.
Although a constructor is called by the runtime implicitly when creating an object, it can also be called explicitly. In this programming tutorial, we will examine constructors, their benefits, and how developers can work with constructors in Java.
Looking to learn Java software development in a class or online course? Check out our list of the Top Online Courses to Learn Java.
What is a constructor in Java?
A constructor is a method or member function of a class whose name is identical to the name of the class it belongs to and whose sole purpose is to initialize the class members. Hence, you can take advantage of a constructor to set initial values to the members of a class.
A Java constructor is called implicitly at the time when you instantiate your class. While you can have several constructors in a class, you can have one – and only one – destructor. Any class in Java must have at least one constructor.
It should be noted that, even if a programmer does not write any constructors in a class, a class provides a constructor implicitly. This constructor provided by the runtime, by default, is called the default constructor. When a class is created using the new operator without any arguments, the default constructor of the class is invoked.
The following code example illustrates how you can define a class in Java:
class MyFirstJavaClass { MyFirstJavaClass() { // This is the constructor body } }
Note that, in the preceding Java code example, the name of the class and the name of the constructor of the class is identical.
What is Constructor Overloading in Java?
Constructor overloading in Java is a method to create multiple constructors for the same class. This allows developers to create multiple constructors in a class that have identical names and differ in their signatures.
It is important to note that the overloaded constructors must have different signatures. The signature of a method in Java comprises the method name, arguments, and the return type.
Since a constructor does not have any return type, overloaded constructors must differ in the type and order of the arguments. In other words, the signature of a constructor comprises the type, number and sequence of its parameters.
When a class has more than one constructor, the compiler uses the overload resolution rules to determine which constructor will be called when you create an instance of that class. The overload resolution rules are used to make sure that the appropriate constructor is called based on the arguments passed in.
Note that the constructor of a class can be overloaded but not overridden since the constructor of a base class and a derived class can never have identical names.
Reading: The Top Java IDEs and Code Editors
Constructors can never be “virtual” in Java
A constructor can neither be virtual nor return any value. To declare a method as virtual, you need to include the keyword virtual in its signature.
Methods of the subclass can override virtual methods. However, you can never override a constructor of a base class in a derived class. You cannot have a virtual constructor, (ie, the constructor of a class can never be virtual), but you can have virtual destructors.
The reason for this is that, when the constructor is being executed, the virtual table or vtable will not be available in memory. The virtual table of a class is only available when the constructor of the class has completed execution.
No-argument and Parameterized Constructors in Java
Constructors can be both no-argument as well as parameterized. As the name suggests, a no-argument constructor is one that does not accept any arguments or parameters. The default constructor is the only no-argument constructor of a class. In other words, you can have one – and only one – no argument constructor in a class.
A parameterized constructor is one that can accept one or more arguments. While you can have one – and only one – no-argument constructor in a class in Java, you can have multiple parameterized constructors.
Now, refer to the code example given below. It shows how you can implement a no-argument constructor for a class in Java:
public class MyClass { private int x; public MyClass() { x = 0; System.out.println(“No-argument constructor called…”); } public static void main(String[] args) { MyClass obj = new MyClass(); } }
Here is a code example that illustrates how you can define an argument constructor for your class in Java:
public class MyClass { private int x; private int y; public MyClass(int i, int j) { x = i; y = j; } public int getValueOfX() { return x; } public int getValueOfY() { return y; } public static void main(String[] args) { MyClass obj = new MyClass(5, 10); System.out.printf(“Printing the value of x : %dn”, obj.getValueOfX()); System.out.printf(“Printing the value of y : %d”, obj.getValueOfY()); } }
Copy constructors in Java
In Java, a copy constructor can be defined as a constructor which creates new instances of a class by making a copy of the current instance of that class. The copy constructor is used when you require a new instance of a class to be created and then be able to change the state of the object without affecting the original object. Hence, the original object’s state remains intact after being copied.
Here is the syntax for using a copy constructor in Java:
MyClass(MyClass obj) { //This is the body of the copy constructor. }
To create a copy constructor for a class, programmers should define a parameter constructor for the class where the type of the parameter is the same as the class type. The following code example shows how you can define a copy constructor in Java:
public class Product { private int id; private String name; public Product(Product product) { this.id = product.id; this.name = product.name; }
Developers can have two types of copy constructors in Java: one that uses shallow copy and another that uses deep copy.
Order of Execution of Constructors in Inheritance in Java
A constructor pertaining to a class is invoked in the order in which the classes have been inherited. On the contrary, the call to destructors follows the reverse order.
The following code example shows how constructors are called in inheritance in Java:
public class HelloWorld { public static void main(String []args) { C obj = new C(); } } class A { public A() { System.out.println(“Constructor of class A called…”); } } class B extends A { public B() { System.out.println(“nConstructor of class B called…”); } } class C extends B { public C() { System.out.println(“Constructor of class C called…”); } }
When you execute the above piece of code, here is how the output will look in the console window:
Figure 1: Demonstrating that constructors are executed in the order of inheritance.
Reading: A Guide to Constructor Chaining in Java.
Final Thoughts on Java Constructors
Although developers can initialize members of a class in other custom methods, it is a good practice to define your constructors for initializing them. Programmers should also define a default constructor explicitly and write your own code to initialize class members – it improves readability as well. It should be noted that in Java, a constructor cannot be abstract, final, static, or native.
read more Java programming tutorials and guides to software development.