Powered by Blogger.

Monday 16 May 2022

Constructor and Constructor Chaining

No comments :
constructor
is the same as a method but the only difference is that the constructor has the same name as the class name. It is used to create an instance of the class. It is called automatically when we create an object of the class. It has no return type. Remember that a constructor cannot be abstract, final, synchronized, and static. We cannot override a constructor.
There are two types of constructor in Java:
  • Default Constructor (also known as a no-argument constructor) 
  • Parameterized Constructor

Constructor chaining: Constructor chaining is the process of calling one constructor from another constructor with respect to current object. 
Constructor chaining can be done in two ways:
  • Within same class: It can be done using this() keyword for constructors in same class 
  •  From base class: by using super() keyword to call constructor from the base class.



The Need of Constructor Chaining
Suppose, there are five tasks to perform. There are two ways to perform these tasks, either implement all the tasks in a single constructor or create separate tasks in a single constructor.
By using the constructor chaining mechanism, we can implement multiple tasks in a single constructor. So, whenever we face such types of problems, we should use constructor chaining. We can make the program more readable and understandable by using constructor chaining.

Watch YouTube video for live working example and develop yourself.