Constructor

Key points of this
  • It’s a method (function).
  • This is executed when you create a new class.
  • It is written in an object-oriented programming language.
I’ll write it simply.

What is a constructor ?

A term used in object- oriented programming languages

and

A method that is executed when an instance is created.

To put it more bluntly,

A function that is executed the moment a class is created.

What is a Constructor?

  • Class: A blueprint that defines what data and operations an object will have.
  • Instance: The actual object created from a class.
  • Method: A function defined inside a class that performs operations on the class’s data.

A constructor is a method that is called automatically when a new object is created from a class. Its purpose is to perform any necessary initial setup for the object.

Example

Here’s an example in Java:

class Example {
    String name;

    // Constructor
    Example() {
        this.name = "default"; // Sets the initial value of 'name' to "default"
    }

    void setName(String _name) {
        this.name = _name; // Method to set the name
    }

    String getName() {
        return this.name; // Method to get the name
    }
}

public class Main {
    public static void main(String[] args) {
        Example ex = new Example(); // Constructor is called here
        System.out.println(ex.getName()); // Outputs "default"
    }
}

In this code, when you create an instance of the Example class, the constructor is automatically called. This sets the name field to "default".

Summary

  • A constructor is a special method that is automatically called when a new object is created from a class.
  • Its role is to perform initialization tasks and ensure the object is set up correctly.
  • Constructors have no return value and must have the same name as the class.