Constructor in java
Constructor is very much similar to method but it doesn’t have any return type, not even void. Constructor is used to initialize the instance variables at the time of object creation. Variables which are defined inside the class and outside the methods are called as the instance variable.
1)Constructor name is always same as class name.
2)Constructor does not have any return type, not even void.
3)Constructor can be overloaded
4)Constructor can not be inherited
5)Constructor can not be overridden because you can not inherit constructor.
6)Constructor gets automatically called whenever we create an object.
Constructor which is provided by compiler is called as default constructor. Default constructor is used to initialize the instance variables to default value at the time of object creation. Whenever we create an object by default, default constructor gets called which shown in below example. Access modifier of default constructor is same as class access modifier. If class access modifier is public then default constructor access modifier is also public.
Parameterized / Custom constructor
Constructor which is not provided by compiler or constructor which is written by the user is called as a parameterized constructor or custom constructor. Parameterized constructor used to initialize the instance variables to the custom value or user defined value at the time of object creation. The access modifier of the parameterized constructor can be anything, it need not be necessary to the same as access modifier of class. In the below example constructor with no input parameter is also a parameterized constructor as it’s written by the user. The Custom or Parameterized constructor with no input parameter behaves the same as the default constructor. which is shown below example.
In the below example of custom or parameterized constructor, instance variables are initialized to custom or user defined value. The user needs to pass the custom values at the time of object creation to custom or parameterized constructor which is shown below.