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

Parameterized constructors


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

          Box( double w, double h, double d)
          {    System.out.println("constructing box");
                width=w;
                height=h;
                depth=d;
         }

         double volume( )
         {       
                   return width*height*depth;
         }
     }
class BoxDemo
     {
               public static void main( String args[])
               {    Box mybox1=new Box(10,20,15);
                     Box mybox2=new Box(3,6,9);
                     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);
                 }
      }


In a parameterised constructor the parameters are passed while creating a object as done here:
Box mybox1=new Box(10,20,15);
The values 10,20 and 15 are passed to the constructor of class box and width, height and depth of box 1 will be initialized to these values.
Similarly we are passing values 3,6 and 9 for box 2, hence its width,height and depth are initialized to 3, 6 and 9.

hence the output of above program will be:

Volume of first box is3000
Volume of second box is162            




To know about unparameterized constructors click here


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

Share the post

Parameterized constructors

×

Subscribe to Prepare For Interview And Recruitment Exams While

Get updates delivered right to your inbox!

Thank you for your subscription

×