Friday 10 August 2012

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;

          Box()
          {    System.out.println("constructing box");
                width=10;
                height=10;
                depth=10;
         }

         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.





No comments:

Post a Comment