Constructor in Java

In this article, we will explore Constructor in Java. We will learn about types of constructor in Java and discuss about the uses of constructors in Java.

Constructor in Java

What is Constructor in Java?

A constructor in Java is a special type of method within a class that is automatically invoked when an object of that class is instantiated or created. Its primary purpose is to initialize the newly created object, setting its initial state and allocating necessary resources.

Key points about constructor in Java:

  1. Name and Signature: Constructors have the same name as the class they belong to and do not have a return type, not even void. This name-based association helps Java recognize that a method is a constructor.
  2. Automatic Invocation: Constructors are automatically called when an object is created using the new keyword. They ensure that the object is properly initialized before it can be used.
  3. Initialization: Constructors are responsible for setting initial values to the object’s fields, performing any necessary setup, and ensuring that the object is in a valid state.
  4. Overloading: Just like regular methods, constructors can be overloaded, meaning a class can have multiple constructors with different parameter lists. This allows you to create objects with varying initializations.
  5. Default Constructor: If no constructors are explicitly defined in a class, Java provides a default constructor with no arguments. However, if you define any constructor, the default constructor is not automatically provided.
  6. Implicit and Explicit Invocation: Constructors can call other constructors using the this() keyword (for constructors within the same class) or the super() keyword (to call a constructor in the parent class).
  7. Inheritance: Constructors are not inherited by subclasses, but the subclass constructor can call the constructor of its superclass using super().
  8. No Return Type: Constructors do not have a return type, not even void, and cannot return values like regular methods.

Constructor in Java Code Example

public class Car {
    private String make;
    private String model;

    // Parameterized constructor
    public Car(String make, String model) {
        this.make = make;
        this.model = model;
    }

    // Getter methods
    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public String getInfo() {
        return "This is a " + make + " " + model + " car.";
    }

    public static void main(String[] args) {
        // Creating objects using the constructor
        Car myCar = new Car("Toyota", "Camry");
        Car anotherCar = new Car("Honda", "Civic");

        // Accessing object properties
        System.out.println("My car is a " + myCar.getMake() + " " + myCar.getModel());
        System.out.println("Another car is a " + anotherCar.getMake() + " " + anotherCar.getModel());

        // Accessing object methods
        System.out.println(myCar.getInfo());
        System.out.println(anotherCar.getInfo());
    }
}

Output

My car is a Toyota Camry
Another car is a Honda Civic
This is a Toyota Camry car.
This is a Honda Civic car.

In this example, the Car class has a parameterized constructor that takes two arguments (make and model) to initialize the object’s attributes.

Types of Constructor in Java

There are several types of constructors based on their parameters and usage. Let’s explore the different types with code examples and their corresponding outputs.

Default Constructor in Java

A default constructor is one that takes no parameters. If you don’t define any constructor in your class, Java automatically provides a default constructor with no arguments.

public class Person {
    
    public Person() {
        System.out.println("Default Constructor in Java");
    }
    
    public static void main(String[] args) {
        Person person = new Person();
    }
}

Output

Default Constructor in Java

Parameterized Constructor in Java

A parameterized constructor takes one or more parameters and initializes the object’s attributes using those parameters.

public class Student {
    private String name;
    private int age;
    
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public static void main(String[] args) {
        Student student = new Student("Alice", 20);
        System.out.println("Name: " + student.getName());
        System.out.println("Age: " + student.getAge());
    }
}

Output

Name: Alice
Age: 20

Copy Constructor in Java

A copy constructor creates a new object by copying the values of another object. It’s often used to create a new instance with the same attributes as an existing object.

public class Book {
    private String title;
    
    public Book(String title) {
        this.title = title;
    }
    
    // Copy constructor
    public Book(Book other) {
        this.title = other.title;
    }
    
    public String getTitle() {
        return title;
    }
    
    public static void main(String[] args) {
        Book original = new Book("The Great Gatsby");
        Book copy = new Book(original);
        
        System.out.println("Original Title: " + original.getTitle());
        System.out.println("Copy Title: " + copy.getTitle());
    }
}

Output

Original Title: The Great Gatsby
Copy Title: The Great Gatsby

Using Private Constructor in Java

Using a private constructor in Java is a technique often employed to implement certain design patterns, such as the Singleton pattern or utility classes.

Let’s take a look at a code example demonstrating the use of a private constructor to implement a Singleton pattern:

public class Singleton {
    private static Singleton instance;

    // Private constructor prevents instantiation from other classes
    private Singleton() {
        System.out.println("Singleton instance created.");
    }

    // Public method to get the Singleton instance
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    public void showMessage() {
        System.out.println("Hello from Singleton!");
    }

    public static void main(String[] args) {
        // Attempting to create multiple instances
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();

        // Both instances point to the same object
        System.out.println("Are instances the same? " + (singleton1 == singleton2));

        // Calling a method on the Singleton instance
        singleton1.showMessage();
    }
}

Output

Singleton instance created.
Are instances the same? true
Hello from Singleton!

In this example, the Singleton class has a private constructor, which means it cannot be instantiated directly from outside the class.

By utilizing a private constructor, we enforce the pattern that only one instance of the class can exist, making it useful for scenarios where a single instance is required to manage a shared resource or maintain application-wide state.

Uses of constructors in Java

Constructors in Java serve a crucial role in object-oriented programming. They facilitate the initialization of objects by setting their initial state and preparing them for use. Let’s explore the various uses of constructors in Java:

  1. Object Initialization: Constructors are responsible for initializing object attributes when an object is created. They set initial values for variables and establish the object’s starting state.
  2. Setting Default Values: Constructors can provide default values to object attributes, ensuring that objects start with predefined values even if no explicit values are provided during instantiation.
  3. Ensuring Consistency: Constructors help ensure that objects are created in a consistent and valid state. By initializing attributes, constructors prevent objects from being in an undefined or nonsensical state.
  4. Encapsulation: Constructors can enforce encapsulation by allowing control over how objects are created and initialized. Private constructors can prevent direct instantiation from outside the class.
  5. Implementing Design Patterns: Constructors are key in implementing design patterns like the Singleton pattern, Factory pattern, and Builder pattern. These patterns rely on specialized constructor implementations to achieve their goals.
  6. Inheritance and Subclasses: Constructors facilitate inheritance by allowing subclasses to call constructors of their superclass. This ensures that attributes and initialization from the parent class are carried over.
  7. Immutable Objects: Constructors are crucial for creating immutable objects, where object state cannot be changed after creation. Once initialized, an immutable object’s state remains constant.

Conclusion: Constructor in Java

In this article, we explored Constructor in Java in great details. We learnt about types of constructor in Java and discussed about the uses of constructors in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *