Constructors are used to initialize the objects only once as soon as a new object is created by using new keyword.
constructors must have its name same as class name and also only placed after new keyword.
constructors are called only once so that no other method can call it.
Better example:- doctors(constructors) use to give all the necessary vaccinations to a newly born child(object) only once.
Gursewak Singh wrote:
but what is need of it if we can initialize a instance variable without it?
as we know basically constructor are use to initialize a instance variable
I am assuming that you are just learning Java -- or even just learning object oriented programming. At this point in your training, objects are probably nothing more than just data structures; and class definitions are probably just a bit of business logic with some instance variables.
As your training continues, constructing an object may include very complex initialization processes. These processes may construct tons of other objects, access databases, access messaging systems, make tons of calls to services, and have tons of combinations to construct your class instances. In that regard, it will probably be much more clearer to why you should provide constructors, than expect your users to configure everything correctly for your instance.