Java: Constructor with example

In this article, we will look into Java Constructor in detail

Constructor in Java

Constructor is a special type of method that is used to initialize an object. Every class has a constructor which is invoked at the time of object creation and provides values

As this provide values at the time of object creation that is why it is called as constructor (constructing wirh default/initial values for object)

 

How constructor gets called

Whenever we create object using ‘new’ keyword, constructor gets called to provide values to the object

For example,

TestConstructor tc = new TestConstructor();

Here,

  • TestConstructor is the name of the class
  • tc’ is the reference object created
  • TestConstructor() is the default constructor

 

Diagrammatic representation

Figure here …..coming up

 

Object creation steps using constructor:

Step 1: Declaring reference variable of type class (i.e.; TestConstructor)

TestConstructor tc;

Step 2: Allocation of heap memory by invoking default constructor using new keyword

new TestConstructor();

Step 3: Assigning newly created heap memory allocation to reference variable

tc = new TestConstructor();

But in practical scenario, we write these three statements in one line, like below

TestConstructor tc = new TestConstructor();

 

Use of constructor in Java

To construct object by initializing values

 

Types of Constructor in Java

  • Default constructor (or no-arg constructor)
  • Parametrized constructor

 

Default constructor:

Constructor which takes zero parameter is called as default constructor. It is also known as no-arg constructor

In other words, constructor with no argument is known as default constructor

 

Example on default constructor

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// default constructor 
	public Employee() {
		System.out.println("Employee class >> Inside default constructor");
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {
		Employee emp = new Employee();
	}
}

Output:

Employee class >> Inside default constructor

 

Execution steps

  • First JVM searches for main() method in class whose access modifier is public
  • And this main() method should be static, as JVM invokes this method without instantiating the object
  • Return type should be void, as there is no need to send any return value to invoking JVM
  • So when JVM executes main() method, then below statement gets fired
    Employee emp = new Employee();
  • This statement in turn will invoke default constructor i.e. no-arg constructor gets executed and prints the message inside default constructor
    Employee class >> Inside default constructor
  • Finally, program exits with success

 

What happens, when there is no constructor explicitly defined in the class?

Employee class is without explicit default constructor

 

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;

	// printEmployeeInfo() method to print details
	void printEmployeeInfo() {
		System.out.println("Id \t: " + employeeId);
		System.out.println("Name \t: " + employeeName);
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {
		Employee emp = new Employee();
		emp.printEmployeeInfo();
	}
}

Output:


Id 	: 0
Name 	: null

 

If there is no constructor defined explicitly by programmer then in that case compiler provides default constructor with no argument and it provides default values to object like

  • 0 for int,
  • null for String
  • false for boolean

 

In above example, compiler provides default constructor since there is no explicit constructor defined by the programmer i.e.;

After compilation below default no-arg constructor is inserted

public Employee() 
{
 }

Try to decompile Java class (i.e.; .class file) using Java compiler (online decompiler tool http://www.showmycode.com/)

1_Java_Constructor_decompiler_class_example

Note: If we explicitly define any constructor (either default no-arg constructor or parametrized constructor) then in that case, compiler doesn’t provide any default no-arg constructor

 

Parametrized constructor:

Constructor which takes one or more parameters is called as parametrized constructor

In other words, constructor with arguments is known as parametrized constructor

 

Example on parametrized constructor:

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;

	// parametrized constructor
	public Employee(int id, String name) {
		System.out.println("Employee class >> Inside parametrized constructor\n");
		this.employeeId = id;
		this.employeeName = name;
	}

	// printEmployeeInfo() method to print details
	void printEmployeeInfo() {
		System.out.println("Id \t: " + employeeId);
		System.out.println("Name \t: " + employeeName);
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {
		Employee emp = new Employee(19, "Rahul Dravid");
		emp.printEmployeeInfo();
	}
}

Output:

Employee class >> Inside parametrized constructor

Id 	: 19
Name 	: Rahul Dravid

 

Use of parametrized constructor in Java

Parametrized constructor provides different way to instantiate objects with distinct values

 

What happens, when there is one parametrized constructor explicitly defined?

In below example, Employee class has one explicit parametrized constructor (2 arguments constructor) and there is no explicit default constructor

Whenever we define any constructor in the class either it is default or parameterized constructor then in that case, compiler doesn’t inserts any default no-arg constructor and results into compilation error as shown below

Compilation Error: The constructor Employee() is undefined

2_Java_Constructor_default_constructor_compilation_error

 

Point to remember about constructor in Java class

  • First and most important point is that, name of the constructor should be same as that of class name
  • And next important point is, constructor don’t have any return type unlike methods (not even void)
  • Every concrete class and abstract class has a constructor
  • Constructor in interfaces is not allowed
  • It can have all Java statements and logic but shouldn’t return any value
  • Constructor can have zero arguments which are called default constructor (or no-arg constructor)
  • Constructor can have one or more input parameters which are called as parametrized constructor
  • If we don’t specify any constructor explicitly then compiler inserts a default no-arg constructor during compilation
  • But when we declare any constructor explicitly either it is no-arg constructor or parametrized constructor, then compiler doesn’t inserts default constructor
  • this() is used to invoke another constructor in the same class, if present must be the first statement of the constructor
  • There cannot be two this() statement in the constructor call
  • Constructor cannot be inherited therefore it can’t be overridden
  • super() is used to invoke another constructor in super class, if present must be the first statement of the constructor
  • But both this() and super() cannot exists at the same time because both cannot be first statement of the constructor which results compilation failure
  • A class can have more than one constructor i.e.; Constructor Overloading
  • All four access modifier i.e.; private, default, protected, public are allowed (no restriction on access modifiers)
  • Private constructor are used for singleton design pattern
  • Non-access modifier like static, final, synchronized, abstract, strictfp, transient, volatile are not allowed

 

References

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

 

Read Also:

Happy Coding !!
Happy Learning !!