Within the Java programming language, a constructor represents a unique method designed for the purpose of initializing objects during the creation of a class. The upcoming section will delve into constructors and their various classifications through illustrative instances.
What is a Constructor in Java?
In Java, a Constructor is a set of code similar to a method that gets invoked when a class instance is generated. This initialization process involves allocating memory for the object. Constructors are unique methods specifically designed for initializing objects.
Whenever an object is instantiated using the new keyword in Java, it invokes a default constructor. If a class does not have any constructors defined, the Java compiler automatically adds a default constructor.
Rules for Creating Java Constructor
Below are the guidelines that must be adhered to when creating constructors in Java:
1. Constructor name must be the same as its class name
The constructor in Java needs to be named after the class it belongs to. This is crucial for the Java compiler to recognize and utilize the constructor during the object instantiation process.
Syntax:
It has the following syntax:
class Student {
Student() {
System.out.println("Constructor called");
}
}
In this case, the constructor is identified as Student since its name aligns with the class name Student.
2. A constructor must have no explicit return type
A constructor does not provide any return value, not even void. Declaring a return type in a constructor will cause it to be interpreted as a regular method rather than a constructor.
Incorrect Example:
class Test {
void Test() { // This is NOT a constructor
System.out.println("Not a constructor");
}
}
Correct Example:
class Test {
Test() {
System.out.println("This is a constructor");
}
}
In this proper instance, the return type "void" has been eliminated from the Test function, rendering it a valid constructor.
3. A Java constructor cannot be abstract, static, final, or synchronized
Constructors in Java are utilized for the instantiation and initialization of objects, hence Java prohibits the use of modifiers with constructors.
Incorrect Example:
class Demo {
static Demo() { // Compilation error
}
}
Correct Example:
class Demo {
Demo() {
System.out.println("Object created");
}
}
In this proper example, we have excluded the "static" keyword to ensure the Demo constructor is valid.
Types of Java Constructors
There are two types of constructors in Java:
- Default Constructor (No-arg Constructor): The default constructor does not take any parameters and is used to initialize an object with default values. If no constructor is defined, Java automatically provides a default constructor.
- Parameterized Constructor: The parameterized constructor accepts parameters and is used to initialize an object with specific values at the time of object creation.
- Copy Constructor: A copy constructor is a special type of constructor that is commonly utilized to create a new object by copying the values of an existing object of the same class.
Let's delve into the various kinds of constructors with a thorough examination of their syntax and suitable illustrations.
1. Java Default Constructor
A constructor without any parameters is referred to as a default constructor.
Syntax
It has the following syntax:
<class_name>(){}
Example of Default Constructor
In this instance, we are defining the parameterless constructor within the Bike class, which will be called during the instantiation of an object.
//Java Program to create and call a default constructor
class Bike{
//creating a default constructor
Bike(){System.out.println("Bike is created");}
}
public class Main{
//main method
public static void main(String args[]){
//calling a default constructor
Bike b=new Bike();
}
}
Output:
Bike is created
Purpose of a default constructor
The default constructor is utilized to assign default values such as 0, null, etc., to the object based on its data type.
Another Example: Displaying the default values
//Let us see another example of default constructor
//which displays the default values
class Student{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
}
//Main class to create objects and calling methods
public class Main{
public static void main(String args[]){
//creating objects
Student s1=new Student();
Student s2=new Student();
//displaying values of the object
s1.display();
s2.display();
}
}
Output:
0 null
0 null
In the class mentioned earlier, if we do not create a constructor, the compiler automatically generates a default constructor for us. This default constructor initializes integer variables to 0 and reference variables to null by default.
2. Java Parameterized Constructor
A constructor that accepts a defined quantity of parameters is referred to as a parameterized constructor.
Syntax
class ClassName {
ClassName(dataType parameter1, dataType parameter2, ...) {
// constructor body
}
}
Use of Parameterized Constructor
The purpose of a parameterized constructor is to assign unique values to individual objects, though it is also possible to assign identical values if needed.
Example of Parameterized Constructor
In this instance, we have defined the constructor for the Student class with two parameters. The constructor can accommodate various numbers of parameters as needed.
//Java Program to demonstrate the use of the parameterized constructor.
class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
}
//Main class to create objects and class methods
public class Main{
public static void main(String args[]){
//creating objects and passing values
Student s1 = new Student(111,"Joseph");
Student s2 = new Student(222,"Sonoo");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Joseph
222 Sonoo
Java Copy Constructor
In Java, the concept of a copy constructor is not directly supported as it is in C++. Nonetheless, it is possible to duplicate the values of one object into another object in Java, resembling the functionality of a copy constructor in C++.
There are the following three ways to copy the values of one object into another:
- By Using a Constructor
- By Assigning the Values of One Object to Another
- By Using the clone Method of the Object Class
Java Copy Constructor Example
In this instance, we will demonstrate how to transfer the values from one object to another by utilizing a Java constructor.
//Java program to initialize the values from one object to another object.
class Student{
int id;
String name;
//constructor to initialize integer and string
Student(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
}
public class Main{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
Copying Values Without using a Constructor
Copying values from one object to another can be achieved by simply assigning the values of the source object to the target object. This method eliminates the necessity of creating a constructor for this purpose.
Example
Consider the following example to illustrate the process of replicating values in Java without the utilization of a constructor.
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}
}
public class Main{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
Constructor Overloading in Java
In Java, a constructor resembles a method in that it doesn't have a return type. Constructors in Java can be overloaded similar to methods in Java.
In Java, constructor overloading involves creating multiple constructors with varying parameter lists to execute different tasks. The compiler distinguishes these constructors based on the number and types of parameters they accept.
Example of Constructor Overloading
To illustrate how constructor overloading works in Java, let's consider an example.
//Java program to overload constructors
class Student{
int id;
String name;
int age;
//creating two arg constructor
Student(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
//creating method to display values
void display(){System.out.println(id+" "+name+" "+age);}
}
//creating a Main class to create instance and call methods
public class Main{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
Constructor Chaining
Constructor chaining in Java refers to the technique of one constructor invoking another constructor within the same class or its superclass when an object is being created. This process commonly involves using this to trigger another constructor within the class or super to activate a constructor in the superclass. This approach of consolidating shared construction operations not only minimizes code duplication but also enhances the clarity of the codebase.
To read more Constructor Chaining in Java
For those new to Java programming, it may be advisable to defer learning about the "this" and "super" keywords as we will cover them in later sections.
Difference Between Constructor and Method in Java
Constructors and methods exhibit several distinctions. These variances are delineated as follows:
| Java Constructor | Java Method |
|---|---|
| A constructor is used to initialize the state of an object. | A method is used to expose the behavior of an object. |
| A constructor must not have a return type. | A method must have a return type. |
| The constructor is invoked implicitly. | The method is invoked explicitly. |
| The Java compiler provides a default constructor if we do not have any constructor in a class. | The method is not provided by the compiler in any case. |
| The constructor's name must be same as the class name. | The method name may or may not be same as the class name. |
Important Points about Constructors
There are several important points about constructors in Java. Some of them are as follows:
- A constructor is automatically called when an object is created using the new keyword.
- If no constructor is defined, Java provides a default constructor that initializes instance variables to default values (0, null, etc.).
- Constructors do not have a return type, not even void.
- A constructor's name must match the class name exactly.
- Constructor overloading is allowed, meaning multiple constructors can be defined with different parameters.
- A constructor can call another constructor within the same class using this, which is known as constructor chaining.
- A constructor can call a superclass constructor using super, which must be the first statement in the constructor.
- Constructors cannot be static, final, abstract, or synchronized in Java.
- Constructors can have access modifiers (public, private, protected, or default). A private constructor is used in singleton patterns.
- Constructors can perform other tasks beyond initialization, such as opening database connections, starting threads, or calling methods.