Constructor in java is one kind of method but you can not call it as method because constructor name is similar as class name and no return type is define for constructor so you can call it as block. it is used to initialize the object’s state. Every time you create an object using new() keyword a constructor is invoked (default constructor is only created by the compiler if we have not created default constructor explicitly) to assign initial values to the data member.
Rules of Constructor in java :
- Constructor name should be same as class name.
- Constructor does not support abstract, final, static and Synchronized keyword.
- default constructor has same access modifier as the class.
Types of java constructors
There are two types of constructors in java :
- Default constructor (no-arg constructor)
- Parameterized constructor
A constructor without parameter is called as default constructor in java. If you have not created any construct in your class then default constructor will be created by compiler if you have created default construct in java then no default construct is created by compiler. Default constructor provides the default values to the object like 0, null etc. depending on the type.
A construct with parameter is called parameterized constructor in java. If you wish to initialize some value to data member instead of default value then you have to use parameterized constructor .
Does constructor return any value ?
There are no return type is defined for construct, but constructor returns current class instance. You can write ‘return’ inside a constructor.
More than one constructor with same name but with different parameter define in the same class is called as constructor overloading in java. below is the example of constructor overloading.
Constructors are not inherited
Dissimilar to statement in a constructor can be inherited by subclasses, constructors are not inherited.
First statement in a constructor must call to this() or super()
The main proclamation of each constructor must be a call to either this() or super().
Constructors can be private
We can make a constructor private to keep the outside world from making another instance of our class. Think about the accompanying class with a private constructor.