What is a constructor in java?

29/03/2013 07:16

Generally constructors are those functions which have same function name as class name.They are also called as special types of fuinctions used to initialize the objects.However there are some restrictions in constructors which are not there in an ordiary functions.They are as follows

  1. Only  values can be assigned in constructors.Neither we can not perform any mathematical operations nor use any kind of print,for etc statements
  2.  In one of my program I had defined 4 methods of defining function.One of that method was using "return" keyword but in constructors we cant use any return keyword

On the bsis of this we can differentiate between constructors and functions

Constructors Functions
  1. Function name is same as class name.
  2. Neither mathmatical operations nor keywords can be used.
  3. They are automatically called in main method.
  1. Function name is different as class name.
  2. Mathematical operations as well as keywords can be used.
  3. They are needed to be called in ain method.