top of page
Writer's pictureThe Tech Platform

What is a Constructor in Java?

Updated: Aug 16, 2023

Have you ever wondered how Java creates and sets up objects when you use the new keyword? Well, that's where constructors come into play! Imagine constructors as the special magic spells that give life to your Java objects.


In this article, we'll explore a constructor in Java and discover what they are, how they work, and why they're essential in making sure your objects start off on the right foot. So, let's start exploring to uncover the secrets of constructors in Java!


Table of content:

Default Constructor

Parameterized Constructor

How to initialize an object's attributes?

How to create an object using a constructor?


What is a Constructor in Java?

In Java, a constructor is a special type of method within a class that is used to initialize the object's state when an instance of the class is created. Constructors are called automatically when an object is instantiated using the new keyword. They provide a way to set initial values to the instance variables of the object and perform any necessary setup operations.


The syntax of a constructor in Java is as follows:

public class ClassName 
{      
    public ClassName() 
    {         
        // Initialization code     
    }  
} 

Where,

  • The public keyword specifies that the constructor is accessible from anywhere.

  • The ClassName keyword is the name of the class.

Here are the key characteristics of a constructor in Java:

  1. Method Name: The constructor method has the same name as the class it belongs to. It does not have a return type, not even void.

  2. No Return Type: Unlike regular methods, constructors don't have a return type, not even void.

  3. Access Modifiers: Constructors can have access modifiers such as public, private, protected, or package-private (default). The access modifier determines from where the constructor can be invoked.

  4. Overloading: Just like regular methods, constructors can also be overloaded, meaning you can have multiple constructors within a class with different parameter lists. This allows you to create objects with different initializations.

  5. Initialization: Constructors are responsible for initializing instance variables and performing any necessary setup operations for the object.

Types of Constructor

There are basically two types of Constructors in Java:

  1. Default Constructor

  2. Parameterized Constructor

1. Default Constructor:

Java provides a default constructor for every class if you do not define any constructors explicitly. However, if you create any constructor within the class, the default constructor must be defined manually if needed. The default constructor has no parameters and performs basic initialization tasks.


For example, the following code is a default constructor for a class called Car:

public class Car 
{      
    private String make;     
    private String model;     
    private int year;      
    public Car() 
    {         
        this.make = "Toyota";         
        this.model = "Camry";         
        this.year = 2023;     
    }  
} 

The Car class has a default constructor that initializes the make, model, and year attributes to the default values of "Toyota", "Camry", and 2023, respectively.


We can create a Car object using the default constructor by using the new keyword:

Car car = new Car(); 

This code will create a Car object with the make, model, and year initialized to the default values.


Here is another example of a default constructor for a class called Car:

public class Car 
{      
    private String make;     
    private String model;     
    private int year;      
    public Car() 
    {         
        // Initialize the attributes to null
        this.make = null;         
        this.model = null;         
       this.year = 0;     
    }  
} 

This code is also a valid default constructor for the Car class. It initializes the make, model, and year attributes to null.

2. Parameterized Constructors:

Parameterized constructors are a powerful feature that allows you to create objects with custom initialization. These constructors take parameters, enabling you to set specific values for object attributes during creation. This concept is known as constructor overloading, where a class can have multiple constructors with different parameter lists.


For example, the following code is a parameterized constructor for a class called Car:

public class Car 
{     
    private String make;     
    private String model;     
    private int year;      
    public Car(String make, String model, int year) 
    {         
        this.make = make;         
        this.model = model;         
        this.year = year;     
    }      
    public static void main(String[] args) 
    {         
        Car myCar = new Car("Toyota", "Camry", 2023);              
        
        System.out.println("Make: " + myCar.make);         
        System.out.println("Model: " + myCar.model);         
        System.out.println("Year: " + myCar.year);     
    } 
}

The Car class has a parameterized constructor that takes three parameters: the make of the car, the model of the car, and the year of the car. The constructor uses these parameters to initialize the make, model, and year attributes of the new object.


We can create a Car object using the parameterized constructor by using the new keyword and passing in the desired values for the make, model, and year:

Car car = new Car("Toyota", "Camry", 2023); 

This code will create a Car object with the make, model, and year initialized to the specified values.

constructor in Java

Here is another example of a parameterized constructor for a class called Car:

public class Car 
{      
    private String make;     
    private String model;     
    private int year;      
    public Car(String make, String model) 
    {         
        this.make = make;         
        this.model = model;         
        this.year = 2023;     
    }  
} 

This code is also a valid parameterized constructor for the Car class. It takes two parameters, the make and model of the car, and uses them to initialize the make and model attributes of the new object. The year attribute is initialized to the default value of 2023.


How to use Constructors?

To use a constructor in Java, you need to:

  1. Create a class with a constructor. The constructor must have the same name as the class.

  2. In the constructor, you can initialize the object's attributes.

  3. To create an object of the class, you can use the new keyword. The new keyword is followed by the name of the class, and then the constructor.

For example, the following code creates a class called Person with a constructor that initializes the name and age attributes:

public class Person {      
    private String name;     
    private int age;      
    public Person() {         
        this.name = "Rahul Roy";         
        this.age = 30;     
    }  
} 

To create an object of the Person class, we can use the following code:

Person person = new Person(); 

This code will create a new Person object with the name "Rahul Roy" and the age of 30.


We can also use parameterized constructors to create objects with specific values. For example, the following code creates a Person object with the name "Rahul Roy" and the age 25:

Person person = new Person("Rahul Roy", 25); 

This code will create a new Person object with the name "Rahul Roy" and the age of 25.


How to initialize an object's attributes?

There are two different methods to initialize an object's attribute:


1. Initializing an object's attribute with a variable:

public class Person 
{      
    private String name;     
    private int age;      
    public Person(String name, int age) 
    {         
        this.name = name;         
        this.age = age;     
    }      
    
    public Person(String name) 
    {         
        this.name = name;         
        this.age = 0;     
    }  
} 

In this code, the Person class has two constructors. The first constructor takes two parameters, the name and the age of the person. The second constructor only takes one parameter, the name of the person. The age of the person is initialized to 0 in the second constructor.


2. Initializing an object's attribute with a method call:

public class Person 
{      
    private String name;     
    private int age;      
    public Person() 
    {         
        this.name = "Rahul Roy";         
        this.age = 30;     
    }      
    
    public Person(String name) 
    {         
        this.name = name;         
        this.age = getRandomAge();     
    }      
    
    private int getRandomAge() 
    {         
        return (int) (Math.random() * 100);     
    }  
} 

In this code, the Person class has two constructors. The first constructor initializes the name and age attributes with the default values. The second constructor only takes one parameter, the name of the person. The age of the person is initialized to a random number between 0 and 100 in the second constructor.


How to create an object using a constructor?

To create an object of the class, you can use the new keyword. The new keyword is followed by the name of the class, and then the constructor.


Here are some examples of how to create objects using constructors in Java:


Example 1: Creating an object with the default constructor:

// Create a class called `Person` with a default constructor. 
public class Person 
{      
    private String name;     
    private int age;  
}  

// Create an object of the `Person` class. 
Person person = new Person(); 

Example 2: Creating an object with a parameterized constructor:

// Create a class called `Person` with a parameterized constructor. 
public class Person 
{      
    private String name;     
    private int age;      
    public Person(String name, int age) 
    {         
        this.name = name;         
        this.age = age;     
    }  
}  

// Create an object of the `Person` class with the name "Rahul Roy" and the age 30. 
Person person = new Person("Rahul Roy", 30); 

Example 3: Creating an object with a constructor that takes a variable number of arguments:

// Create a class called `Person` with a constructor that takes a variable number of arguments. 
public class Person 
{      
    private String name;     
    private int age;      
    public Person(String... names) 
    {         
        this.name = names[0];         
        this.age = names.length;     
    }  
}  

// Create an object of the `Person` class with the names "Rahul Roy", "Jane Doe", and "Mary Doe". 
Person person = new Person("Rahul Roy", "Jane Doe", "Mary Doe");

Overloaded Constructor in Java

In Java, overloaded constructors are multiple constructors with the same name but different parameter lists. This allows us to create different types of objects with different initial values.


For example, we could have a class called Car with two overloaded constructors:

public class Car 
{      
    private String make;     
    private String model;     
    private int year;      
    public Car() 
    {         
        this.make = "Toyota";         
        this.model = "Camry";         
        this.year = 2023;     
    }      
    
    public Car(String make, String model, int year) 
    {         
        this.make = make;         
        this.model = model;         
        this.year = year;     
    }  
} 

The first constructor is the default constructor. It initializes the make, model, and year attributes to the default values of "Toyota", "Camry", and 2023, respectively.


The second constructor is a parameterized constructor. It allows us to create a Car object with the specified make, model, and year.


When we create a new object of the Car class, the compiler will choose the most appropriate constructor to use based on the parameters that we pass in. For example, if we pass in the values "Toyota", "Camry", and 2023, the compiler will use the second constructor to create the object. If we don't pass in any parameters, the compiler will use the default constructor to create the object.


Benefits of Constructor in Java:

There are many benefits to using a constructor in Java. Here are a few of the most important ones:

  • Initialization: Constructors can be used to initialize the attributes of an object. This is especially important when we need to initialize the attributes with specific values.

  • Encapsulation: Constructors can help to encapsulate the attributes of an object. This means that the attributes are hidden from the outside world and can only be accessed by the methods of the class.

  • Reusability: Constructors can be used to create reusable objects. This is because we can use the same constructor to create multiple objects with the same attributes.

  • Flexibility: Constructors can be used to create different types of objects with different initial values. This is possible because we can overload constructors.

  • Error prevention: Constructors can help to prevent errors. This is because they can be used to ensure that the attributes of an object are initialized with the correct values.

In general, it is a good practice to use constructors in Java whenever possible. This will help to ensure that our code is more efficient, reusable, and error-free.


Here are some additional benefits of using a constructor in Java:

  • Code readability: Constructors can make our code more readable by grouping the code that initializes the attributes of an object together. This makes it easier to understand what the object does and how it works.

  • Code maintainability: Constructors can make our code more maintainable by making it easier to add or change the attributes of an object. This is because we only need to change the constructor code, instead of changing the code in every place where the object is created.

  • Testability: Constructors can make our code more testable by making it easier to create objects with the correct initial values. This makes it easier to write unit tests for our code.


Conclusion

Constructor in Java forms the backbone of object-oriented programming in Java. By understanding their role, syntax, and importance, you're well on your way to creating well-structured, effective, and easily maintainable Java programs. Embrace constructors as a powerful tool for building objects that are initialized correctly and serve their intended purposes.

Recent Posts

See All

Comments


bottom of page