Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is a constructor in Java?

It can be tedious to initialize all of the variables in a class each time an instance is created. JAVA allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of constructor.
A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined it is automatically called immediately after the object is created before the new operator completes.
Constructor have no return type not even void. This is because the implicit return type of a constructor is the class type itself.

For example:

class Box
    {    double width;
          double height;
          double depth;

          {    System.out.println("constructing box");

         double volume( )
                   return width*height*depth;
class BoxDemo
               public static void main( String args[])
               {    Box mybox1=new Box( );
                     Box mybox2=new Box( );
                     double vol;
                     vol=mybox1.volume( );
                     System.out.println("Volume of first box is"+vol);
                     vol=mybox2.volume( );
                     System.out.println("Volume of second box is"+vol);

the output of this program will be :   (How to compile and run a program)

Volume of first box is1000
Volume of second box is1000

* In order to pass different parameters to both boxes we have to use Parameterized constructor.

This post first appeared on Prepare For Interview And Recruitment Exams While, please read the originial post: here

Share the post

What is a constructor in Java?


Subscribe to Prepare For Interview And Recruitment Exams While

Get updates delivered right to your inbox!

Thank you for your subscription