# 15) Constructors

### Real Life Example:

What happens when you open a new bank account? Depending on the services your bank provides, you may be assigned a new bank account number, provided with a check- book, and given access to a new online account the bank has created for you. These details are created and returned to you as part of setting up your new bank account.

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTY_3PX8AP7ttJUDE10%2F-LTY_zWRHFF5Y5ipy8O1%2FScreen%20Shot%202018-12-12%20at%2011.34.15%20PM.png?alt=media\&token=91aec413-8e19-496d-8d1d-3c1ef39c11e6)

\


### **Definition:**

Constructor is a special method which is used to construct an object or create an object for a class.

Constructor does not return any value or does not have any Return type.

Whenever an object of class is created using **new** operator constructor will be executed.&#x20;

### **Why Contructor?**

We can use constructor to create object, without constructor we cannot create Object.&#x20;

**Rules to develop constructor:**

* Constructor named should be exactly same as Class name.&#x20;
* Constructor should not have return type, should always be non-static should not return any value.&#x20;
* Constructor is also called as Non-static initializer, which is used to initialize the object of a class.&#x20;
* No static and return type allowed.&#x20;
* Constructor should be there for every class.&#x20;
* If the programmer has not developed a constructor for class then there will be default constructor in that class.&#x20;

### **Default Constructor:**

The constructor developed by the compiler at compile-time is called as Default constructor. If a programmer has not developed a constructor for class then compiler will develop the default constructor.

### **Differences:**

| **Methods**                                              | **Constructor**                                                  |
| -------------------------------------------------------- | ---------------------------------------------------------------- |
| Method can have any name; it can have a class name also. | Constructor name Should be similar to the Class name.            |
| Method must have return type at least void               | Constructor should have Return type not even void                |
| Method can be static or non-static.                      | Constructor should always be non-static                          |
| Method may or may not return value.                      | Constructor cannot return value.                                 |
| Java does not provide Default Method                     | Java provides Default Constructor.                               |
| Method cannot be used for Object creation.               | Constructor will be used for object creation using new operator. |

### **Note: Steps in Object creation**

* New operator will allocate the new address space randomly in the heap memory.&#x20;
* All the Non-Static members of class will be loaded onto the address space with default values.&#x20;
* Constructor body will be executed on Stack memory like a method.&#x20;
* Object address will be assigned to Reference variables.&#x20;

### **Why Programmer should write Constructor if java provides Default Constructor?**

If the programmer needs to initialize the instance variable then programmer can perform the initialization in Constructor.

If the programmer wants to perform some start up activities whenever an object is created for the class, then programmer will reuse the Constructor body and all the startup code will be developed inside the Constructor.

### **Types of Constructor:**

1. Parameterized Constructor:  The Constructor which is developed with some arguments.  Example: A(int I)&#x20;
2. No-Arguments Constructor: The Constructor which is developed without arguments. Example: A()&#x20;

\*\* Default Constructor falls under No-Arguments Constructor.

### **Note:**

* To create the object for a class we should utilize available Constructor of that class.&#x20;
* If programmer develops a Constructor for class then java does not provide a default Constructor.&#x20;

### **Constructor Overloading:**

Developing multiple Constructors for a class with the variation in the Data-type, members and position of arguments is called Constructor overloading.

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Simple1 {
	Simple1() {
		System.out.println("Running Constructor");
	}

	public static void main(String[] args) {
		System.out.println("Main Starts");
		Simple1 s1 = new Simple1();
		System.out.println("Main Ends");
	}
}
```

**Output:**

Main Starts

Running Constructor

Main Ends

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Simple22 {
	Simple22() {
		System.out.println("Running Demo1 constructor");
	}

	public static void main(String[] args) {
		System.out.println("Main Starts");
		Simple22 s2 = new Simple22();
		System.out.println("------------");
		Simple22 s22 = new Simple22();
		System.out.println("Main Ends");
	}
}
```

**Output:**

Main Starts

Running Demo1 constructor

\------------

Running Demo1 constructor&#x20;

Main Ends

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Simple3 {
	/*
	 * DefaultConstructor Simple3() { }
	 */
	public static void main(String[] args) {
		System.out.println("Main Starts");
		Simple3 s3 = new Simple3(); // Call to default constructor System.out.println("Main Ends");
	}
}
```

**Output:**

Main Starts

Main Ends

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Simple4 {
	void Simple4() {
		System.out.println("Constructor ?");// Method with class name.
	}

	public static void main(String[] args) {
		System.out.println("Main Starts");
		Simple4 s4 = new Simple4();
		System.out.println("Main Ends");
		System.out.println("-----------");
	}
}
```

**Output:**

Main Starts

Main Ends

\-----------

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Simple55 {
	int stdId;

	Simple55() {
		System.out.println("Running Constructor");
	}

	public static void main(String[] args) {
		System.out.println("Main Starts");
		Simple55 s5 = new Simple55();
		System.out.println("Value of stdId is :" + s5.stdId);
		System.out.println("--------------------");
		Simple55 s55 = new Simple55();
		System.out.println("Value of stdId is :" + s55.stdId);
		System.out.println("Main Ends");
	}
}
```

**Output:**

Main Starts&#x20;

Running Constructor&#x20;

Value of stdId is :0

\--------------------

Running Constructor&#x20;

Value of stdId is :0&#x20;

Main Ends

**Example:** **Parametrized Constructor**&#x20;

```java
package com.gs.ilp.corejava.Constructor;

public class Simple66 {
	int empId;

	Simple66(int id) {
		empId = id;
	}

	public static void main(String[] args) {
		System.out.println("Main Starts");
		Simple66 s6 = new Simple66(10);
		System.out.println("Employee id is:" + s6.empId);
		Simple66 s66 = new Simple66(20);
		System.out.println("Employee id is:" + s66.empId);
		System.out.println("Main Ends");
	}
}

```

**Output:**

Main Starts&#x20;

Employee id is:10&#x20;

Employee id is:20&#x20;

Main Ends

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Simple7 {
	int stdId;
	String stdName;

	Simple7(int id, String name) {
		stdId = id;
		stdName = name;
	}

	public static void main(String[] args) {
		System.out.println("Main Starts");
		Simple7 s7 = new Simple7(1, "JSM");
		System.out.println("1st student id is:" + s7.stdId);
		System.out.println("1st student name is:" + s7.stdName);
		System.out.println("-------------------------");
		Simple7 s77 = new Simple7(1, "SMP");
		System.out.println("1st student id is:" + s77.stdId);
		System.out.println("1st student name is:" + s77.stdName);
		System.out.println("Main Ends");
	}
}
```

**Output:**

Main Starts

1st student id is:1

1st student name is:JSM

\-------------------------

1st student id is:1

1st student name is:SMP&#x20;

Main Ends

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Circle {
	double radius;

	Circle(double r) {
		radius = r;
		double a = 3.14 * radius * radius;
		System.out.println("Area is:" + a);
	}

	public static void main(String[] args) {
		Circle c1 = new Circle(2.3);
		Circle c2 = new Circle(5.2);
	}
}
```

**Output:**

Area is:16.610599999999998

Area is:84.90560000000002

**Example:**&#x20;

```java
package com.gs.ilp.corejava.Constructor;

public class A {
	A() {
		System.out.println("From A()");
	}

	A(int a) {
		System.out.println("From A(int a)");
	}

	A(double d) {
		System.out.println("From A(double d)");
	}

	A(int i, double d) {
		System.out.println("From A(inti,double d)");
	}

	public static void main(String[] args) {
		A a1 = new A();
		A a11 = new A(50);
		A a111 = new A(50.1);
		A a1111 = new A(50, 50.8);
		A a11111 = new A(50, 60.9);
	}
}
```

**Output:**

From A()&#x20;

From A(int a)

From A(double d)&#x20;

From A(inti,double d)&#x20;

From A(inti,double d)

**Example:**

```java
package com.gs.ilp.corejava.Constructor;

public class Student {
	String stdName;
	int stdId;
	int age;

	Student(String name, int id, int a) {
		stdName = name;
		stdId = id;
		age = a;
	}

	Student(String name, int id) {
		stdName = name;
		stdId = id;
	}

	public static void main(String[] args) {
		Student s1 = new Student("JSM", 10, 90);
		System.out.println("1st student id is:" + s1.stdId);
		System.out.println("1st student Name is:" + s1.stdName);
		System.out.println("1st student age is:" + s1.age);
		Student s2 = new Student("SMP", 20);
		System.out.println("1st student id is:" + s2.stdId);
		System.out.println("1st student Name is:" + s2.stdName);
	}
}
```

**Output:**

1st student id is:10

1st student Name is:JSM&#x20;

1st student age is:90&#x20;

1st student id is:20

1st student Name is:SMP

### **What if you implement only parameterized constructor in class**

```java
package com.gs.ilp.corejava.Constructor;

public class Example3 {
	private int var;

	public Example3(int num) {
		var = num;
	}

	public int getValue() {
		return var;
	}

	public static void main(String args[]) {
		Example3 myobj = new Example3();
		System.out.println("value of var is: " + myobj.getValue());
	}
}
```

**Output**: It will throw a compilation error. The reason is, the statement Example3 myobj = new Example3() is invoking a default constructor which we don’t have in our program. When you don’t implement any constructor in your class, compiler inserts the default constructor into your code, however when you implement any constructor (in above example I have implemented parameterized constructor with int parameter), then you don’t receive the default constructor by compiler into your code.

If we remove the parameterized constructor from the above code then the program would run fine, because then compiler would insert the default constructor into your code.

**Can we Override constructor?**

NO, because constructor will not be inherited to sub class but for method overriding inheritance is mandatory.

**Can we override main method?**

NO, because main is static method, static method will not be inherited to sub class and for method overriding inheritance is mandatory.

**Can we Override Static members?**

NO, because static methods will not be inherited to sub class but for method overriding inheritance is mandatory.

**Q. What is constructor chaining in Java?**

Constructor chaining is a phenomenon of calling one constructor from another constructor of same class. Since constructor can only be called from another constructor in Java, constructor chaining is used for this purpose.

```java
package com.gs.ilp.corejava.Constructor;

public class Test {
	Test() {
		this(10);
	}

	Test(int x) {
		System.out.println("x=" + x);
	}
}
```

### What happens if you define a return type for a constructor?

Java will treat it as another method, not a constructor, which also implies that it won’t be called implicitly when you create an object of its class:

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTcbnAy0QjzDOAPMnRi%2F-LTcjnzi8vkiK7FNAjMF%2FScreen%20Shot%202018-12-13%20at%2011.35.32%20PM.png?alt=media\&token=9c7c3833-cd60-4a00-a5d2-97fbdeabc68d)

**How do you execute such a method?**&#x20;

By calling it explicitly, as in the following code (modified code is in bold):

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTcbnAy0QjzDOAPMnRi%2F-LTckExlyZm8Zc82gt5j%2FScreen%20Shot%202018-12-13%20at%2011.37.40%20PM.png?alt=media\&token=1e3fc060-1714-417c-b817-a7ee76226505)

### What happens if you don’t define any constructor in a class?

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTcbnAy0QjzDOAPMnRi%2F-LTcqgXk5pNsTgWufUM1%2FScreen%20Shot%202018-12-14%20at%2012.05.53%20AM.png?alt=media\&token=75ae9cfd-4e6f-4d02-8f08-920498e8cf26)

#### Behind the scenes:

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTcbnAy0QjzDOAPMnRi%2F-LTcs4nR5m_1sjJkKiPT%2FScreen%20Shot%202018-12-14%20at%2012.11.57%20AM.png?alt=media\&token=e20944b0-56eb-42eb-9f7b-a67e85633571)

**What happens if you add another constructor to the class Employee, as in the following example?**

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTcbnAy0QjzDOAPMnRi%2F-LTczGoxSoSWmKft-Ji4%2FScreen%20Shot%202018-12-14%20at%2012.42.40%20AM.png?alt=media\&token=54e4f222-8301-4f50-8b4d-4bac984b7d22)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTcbnAy0QjzDOAPMnRi%2F-LTczL-kPt3Gg3Z6V2Sc%2FScreen%20Shot%202018-12-14%20at%2012.42.59%20AM.png?alt=media\&token=07890783-3385-4fd0-baf3-67aa6f5deb9b)

Java defines a default constructor if and only if you don’t define a constructor. If a class doesn’t define a constructor, the compiler will add a default, no-argument constructor to the class. But if you modify the class later by adding a constructor to it, the Java compiler will remove the default, no- argument constructor that it initially added to the class.

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTcbnAy0QjzDOAPMnRi%2F-LTcz_rYNc61pSfjKehl%2FScreen%20Shot%202018-12-14%20at%2012.44.34%20AM.png?alt=media\&token=2c0e0757-ef97-4a16-8a8d-63a1bd89941c)

