Tuesday, 20 December 2011

05 - Constructors

//Program to demostrate the use of constructors

/*
    Until now we are initializing the instance variables length, width and height by using
    the setDim() method.

    If you want the instance variables of an object to hold some default values other than
    zeros, when the objects are created, then you can use constructors.

    Let us discuss about constructors:
    1) Constructor is a special kind of method which is use to initialize the instance variables.
    2) Constructor has the same name as the class name.
    3) Constructor is invoked/called automatically when an object is created.
    4) Constructor has no return type like the methods. Implicit return type of a constructor is
       the class itself.

    If you want to execute a set of statements when each object is created, you can write them in
    the constructor.

    Syntax for declaring a constructor:
    class-name()
    {
        statements;
    }

    For example if you want to create a constructor for our Box class, you can write like this:
    Box()
    {
        length = 10;
        width = 20;
        height = 30;
    }

    In java all the instance variables are by default initialized to zero. Because in every class
    there will be a "default constructor" which initializes all the instance variables to zero.

    As methods can accept parameters, constructors also accept parameters as shown below. By using
    parameters we generalize the method/constructor to accept any values you want.

    Box(int l,int w,int h)
    {
        length = l;
        width = w;
        height = h;
    }

    Lets use a constructor to initialize the instance variables, instead of using the setDim() method.
*/

class Box
{
    int length;
    int width;
    int height;

    Box(int l,int w,int h)
    {
        length = l;
        width = w;
        height = h;
    }

    void volume()
    {
        System.out.println("Volume of Box is: "+(length*width*height));
    }
}

class BoxDemo
{
    public static void main(String args[])
    {
        Box b1 = new Box(10,20,30); //Constructor is automatically called
        b1.volume();
        //Box b2 = new Box(); //will give error because there is no zero parameter constructor in "Box" class.
    }
}

Download only the program: http://paste2.org/followup/1832514

No comments:

Post a Comment