Java Constructors


In Java, a constructor is a special type of method used to initialize objects when they are created. It is automatically invoked when an object of a class is created. Constructors play a crucial role in setting up initial values for object attributes and ensuring that objects are properly initialized before use.

In this guide, we'll explore Java constructors in detail, covering their types, syntax, how they work, and examples to help you understand their usage.

Table of Contents

  1. What is a Java Constructor?
  2. Types of Constructors
  3. Constructor Syntax in Java
  4. Constructor Example in Java
  5. Default Constructor
  6. Parameterized Constructor
  7. Constructor Overloading
  8. Constructor with this Keyword
  9. Constructor Chaining

What is a Java Constructor?

A constructor in Java is a block of code used to initialize an object. When an object is created using the new keyword, the constructor is automatically invoked to set up initial values for the object's properties (instance variables). Constructors do not have a return type and their name must be the same as the class name.

Key Characteristics:

  • Name: The constructor's name must be the same as the class name.
  • No return type: Constructors do not return any value, not even void.
  • Automatically called: Constructors are invoked when an object is created using the new keyword.

Types of Constructors

In Java, constructors can be broadly classified into two types:

  1. Default Constructor: A constructor that takes no arguments and initializes the object with default values.
  2. Parameterized Constructor: A constructor that takes arguments to initialize an object with custom values.

Constructor Syntax in Java

Default Constructor Syntax:

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

Parameterized Constructor Syntax:

class ClassName {
    // Constructor with parameters
    public ClassName(parameter1, parameter2, ...) {
        // Initialization code
    }
}

Constructor Example in Java

Let's look at a basic example of using a constructor to initialize an object.

Example: A Simple Constructor

public class Car {
    // Instance variables
    String model;
    int year;

    // Constructor to initialize the object
    public Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    // Method to display car details
    public void display() {
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }
}

Main Method to Create an Object:

public class Main {
    public static void main(String[] args) {
        // Create a Car object and pass values to the constructor
        Car myCar = new Car("Toyota Corolla", 2020);
        
        // Call the display method to show car details
        myCar.display();
    }
}

Output:

Model: Toyota Corolla
Year: 2020

In this example, the Car class has a parameterized constructor that takes two parameters (model and year). When the object myCar is created, the constructor is called to initialize these values.


Default Constructor

A default constructor is a constructor that doesn't take any parameters. If you do not explicitly define a constructor, Java provides a default constructor with no arguments. This constructor initializes the instance variables with default values (e.g., 0 for numeric types, null for object references).

Example: Default Constructor

public class Book {
    String title;
    String author;

    // Default constructor
    public Book() {
        title = "Unknown";
        author = "Unknown";
    }

    // Method to display book details
    public void display() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
    }
}

Main Method to Create an Object:

public class Main {
    public static void main(String[] args) {
        // Create a Book object using the default constructor
        Book myBook = new Book();
        
        // Call the display method to show book details
        myBook.display();
    }
}

Output:

Title: Unknown
Author: Unknown

In this example, since the Book class doesn't have a parameterized constructor, Java provides a default constructor that initializes the title and author fields to "Unknown".


Parameterized Constructor

A parameterized constructor allows you to pass arguments when creating an object. This helps initialize the object with specific values.

Example: Parameterized Constructor

public class Laptop {
    String brand;
    double price;

    // Parameterized constructor
    public Laptop(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }

    // Method to display laptop details
    public void display() {
        System.out.println("Brand: " + brand);
        System.out.println("Price: " + price);
    }
}

Main Method to Create an Object:

public class Main {
    public static void main(String[] args) {
        // Create a Laptop object using the parameterized constructor
        Laptop myLaptop = new Laptop("Dell", 799.99);
        
        // Call the display method to show laptop details
        myLaptop.display();
    }
}

Output:

Brand: Dell
Price: 799.99

In this example, the Laptop class has a parameterized constructor that accepts the brand and price as arguments.


Constructor Overloading

Constructor overloading is similar to method overloading. It allows you to define multiple constructors with different parameter lists. This provides flexibility in object creation.

Example: Constructor Overloading

public class Smartphone {
    String brand;
    double price;

    // Constructor with no parameters
    public Smartphone() {
        brand = "Unknown";
        price = 0.0;
    }

    // Constructor with one parameter
    public Smartphone(String brand) {
        this.brand = brand;
        price = 0.0;
    }

    // Constructor with two parameters
    public Smartphone(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }

    // Method to display smartphone details
    public void display() {
        System.out.println("Brand: " + brand);
        System.out.println("Price: " + price);
    }
}

Main Method to Create Objects:

public class Main {
    public static void main(String[] args) {
        // Create objects using different constructors
        Smartphone phone1 = new Smartphone();
        Smartphone phone2 = new Smartphone("Samsung");
        Smartphone phone3 = new Smartphone("Apple", 999.99);

        phone1.display();
        phone2.display();
        phone3.display();
    }
}

Output:

Brand: Unknown
Price: 0.0
Brand: Samsung
Price: 0.0
Brand: Apple
Price: 999.99

In this example, we overloaded the constructor to provide different ways of initializing the Smartphone object.


Constructor with this Keyword

In Java, the this keyword is used inside a constructor to refer to the current object. It is commonly used when the parameter name is the same as the instance variable name to differentiate between them.

Example: Using this Keyword

public class Person {
    String name;
    int age;

    // Constructor with 'this' keyword to distinguish between instance variables and parameters
    public Person(String name, int age) {
        this.name = name;  // Assign the parameter value to the instance variable
        this.age = age;    // Assign the parameter value to the instance variable
    }

    // Method to display person details
    public void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

Main Method to Create an Object:

public class Main {
    public static void main(String[] args) {
        // Create a Person object
        Person person = new Person("John", 30);
        
        // Call the display method to show details
        person.display();
    }
}
public class Main {
    public static void main(String[] args) {
        // Create a Person object
        Person person = new Person("John", 30);
        
        // Call the display method to show details
        person.display();
    }
}

Output:

Name: John
Age: 30

Here, the this keyword differentiates between the instance variables name and age and the parameters passed to the constructor.


Constructor Chaining

Constructor chaining refers to the technique of calling one constructor from another constructor in the same class or in a superclass. This can help avoid code duplication and improve readability.

Example: Constructor Chaining in Java

public class Animal {
    String name;

    // Constructor of Animal class
    public Animal(String name) {
        this.name = name;
    }
}

public class Dog extends Animal {

    // Constructor of Dog class
    public Dog(String name) {
        // Calling the constructor of the superclass (Animal)
        super(name);
    }

    // Method to display dog details
    public void display() {
        System.out.println("Dog's name: " + name);
    }
}

Main Method to Create an Object:

public class Main {
    public static void main(String[] args) {
        // Create a Dog object
        Dog dog = new Dog("Buddy");

        // Call the display method to show details
        dog.display();
    }
}

Output:

Dog's name: Buddy

In this example, the constructor of the Dog class calls the constructor of the Animal class using super(name) to initialize the name attribute.