Constructor in java is a special function that is used to initialize member variables of a class. Some of the key features of constructors are:
- Constructor is by the name of class.
- Default constructor is created automatically if no constructor is created by the user. If user creates a constructor then no default constructor will be created automatically.
- Constructor overloading can be done by changing arguments in signature of constructor.
- Access specifiers such as public, private or protected can be applied to constructors. There visibility for constructors is similar to normal functions. Example: private constructor can be accessed within the class only.
- We can call constructors within the class or the parent class using keywords ‘this‘ and ‘super‘ respectively. This is called as Constructor Chaining.
- We cannot define any return type to constructor. Constructors by default return instance of the class.
To understand the above features in detail we have divided them in few sections :-