What is a constructor? When do we declare a constructor? Explain with example.


Q.) What is a constructor? When do we declare a constructor? Explain with example.

Subject: Object Oriented Programming and Methodology

Constructor

Definition: A constructor is a special method of a class that is invoked when an object of that class is created. It is responsible for initializing the instance variables of the object to their initial values. A constructor has the same name as the class and does not have any return type.

When to Declare a Constructor?

A constructor is declared whenever a class is created. It is not mandatory to declare a constructor in Java, but it is considered good practice to do so. If you do not declare a constructor, Java will provide a default constructor for you. However, the default constructor will not initialize any instance variables, which can lead to unexpected behavior.

Types of Constructors

There are two types of constructors:

  • Default Constructor: The default constructor is provided by Java if you do not declare one yourself. It does not take any arguments and does not initialize any instance variables.

  • Parameterized Constructor: A parameterized constructor is a constructor that takes arguments. These arguments are used to initialize the instance variables of the object.

Example:

The following is an example of a class with a constructor:

class Person {
    String name;
    int age;

    public Person() {
        name = "";
        age = 0;
    }

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

In the above example, the Person class has two constructors:

  • The first constructor is the default constructor. It takes no arguments and initializes the instance variables name and age to "" and 0, respectively.
  • The second constructor is a parameterized constructor. It takes two arguments, name and age, and initializes the instance variables name and age to the values of the arguments.

Points to Remember:

  • A constructor is invoked when an object of the class is created.
  • A constructor has the same name as the class.
  • A constructor does not have any return type.
  • It is not mandatory to declare a constructor in Java, but it is considered good practice to do so.
  • If you do not declare a constructor, Java will provide a default constructor for you.
  • The default constructor does not initialize any instance variables.
  • You can declare parameterized constructors to initialize the instance variables of the object when it is created.