> For the complete documentation index, see [llms.txt](https://qatesting.gitbook.io/qa/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://qatesting.gitbook.io/qa/java/oops/constructor.md).

# Constructor

## 👷‍♂️ What is a Constructor?

A **constructor** in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is instantiated.

> It runs automatically whenever we create a new Person object using the new keyword.
>
> Inside the constructor we can put code to set initial values for object attributes. For example:
>
> public Person(String name) {
>
> this.name = name;\
> }
>
> Now when we do:
>
> Person p = new Person("Adam");
>
> The constructor assigns "Adam" to the name attribute.

<figure><img src="https://i.ytimg.com/vi/6UfXKx2Q59Q/maxresdefault.jpg" alt=""><figcaption></figcaption></figure>

For example:

```java
public class Person {

  // Constructor
  public Person() {
    // Initialization code goes here
  }
  
}
```

The constructor always has the same name as the class and no return type.

## 🏗️ Rules for Constructors in Java 🏗️

Constructors are special methods used to initialize objects in Java. There are some important rules around defining and using constructors.

### 🏠 Rules for Default Constructors 🏠

A default constructor has the following rules:

* It has the same name as the class
* It has no parameters
* It is generated automatically if no constructors are defined
* The default constructor initializes all member variables to default values

For example:

```java
public class Person {

  private String name;

  // Default constructor generated automatically
  public Person() {
    name = ""; 
  }

}
```

The default constructor sets `name` to an empty string.

### 🛠️ Rules for Parameterized Constructors 🛠️

Some rules for parameterized constructors are:

* Can have any number of parameters, with any types
* Must have the same name as the class
* Are defined by the programmer
* Initialize fields using values passed as parameters

For example:

```java
public class Person {

  private String name;
  
  // Parameterized constructor
  public Person(String name) {
    this.name = name;
  }

}
```

This constructor initializes the `name` field using a passed parameter.

So following the rules for default and parameterized constructors allows proper initialization of objects in Java.

## 🔨 Key Notes

* A constructor is a special method with the class name
* It is called automatically when an object is created
* It is used to initialize the object's state
* If no constructor is defined, Java provides a default one

So constructors allow objects to be initialized right after instantiation.

## 🛠️ In Simple Terms

The constructor is the initialization method of a class which sets up the new object when it is created. It runs automatically when a new object is made to get the object ready for use.

So in Java, constructors setup new objects!

<figure><img src="https://images.unsplash.com/photo-1610876691676-bb447cca5fd2?crop=entropy&#x26;cs=srgb&#x26;fm=jpg&#x26;ixid=M3wxOTcwMjR8MHwxfHNlYXJjaHw0fHxjb25zdHJ1Y3RvcnxlbnwwfHx8fDE2ODk5MzEwMDl8MA&#x26;ixlib=rb-4.0.3&#x26;q=85" alt=""><figcaption></figcaption></figure>

## Two Types of Constructors 🏗

Constructors initialize an object when it is created. They have the same name as the class and differs by the parameter list.

There are two types of constructors in Java:

### **Default Constructor 🏗️**

* Created automatically if no constructor is defined
* Has no parameters
* Can be defined explicitly

```java
class Person {
   String name;

   Person() {      
     // Default constructor
   }
}

Person p = new Person(); 
```

### **Parameterized Constructor ⚙️**

* Created by the programmer
* Has parameters to initialize the object

```java
class Person {
   String name;

   Person(String name) {  
     this.name = name;     
   }
}

Person p = new Person("John");
```

Here `name` parameter is used to initialize the `name` field.

**this** keyword refers to the current object.

## Constructor Chaining ⛓

When one constructor calls another, it is known as constructor chaining. This allows reusing code and improving maintainability.

```java
class Person {
  
  String name;
  int age;  
  
  Person() { 
    this("John Doe");     // Invoking another constructor
  }
  
  Person(String name) {    
    this(name, 0);       
  }
  
  Person(String name, int age) {
    this.name = name;     
    this.age = age;   
  }   
}
```

Here `this()` is used to invoke another constructor of the same class.

The constructor chain finally invokes the most specific constructor which initializes all fields.
