Tuesday, 20 December 2011

03 - Creating and calling methods

//Creating and calling methods

/*
    In the previous program, I have written the logic for computing the volume in the execution
    class, i.e "BoxDemo" class. It is always good to write the entire logic in the logic class
    i.e in our "Box" class.

    Also I am initializing the instance variables length, width and height in the "BoxDemo" class.
    I will also push those statements into the "Box" (logic) class.

    This can be acheived by creating methods (functions in C language) in the "Box" class.

    Lets see how to define methods.

    Syntax for declaring methods:
    return-type methodName(parameters list)
    {
        statements;
    }

    As classes have a naming convention, methods also have a naming convention in java.
    If a method name consists of multiple words, then the first word will be in lower case
    and the first letters in the remaining words will be in uppercase.

    If the method name is "methodname" then you should write as "methodName".

    Also remember that class names and method names have no white spaces.

    Ok. Now, lets declare a method for intializing the instance variables length,width and height
    as "setDim()" and also for computing the volume lets declare another function "volume()"
*/

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

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

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

/*
    In the above "Box" class setDim is a method accepting three parameters l,w,h
   
    To execute these methods, they must be called from somewhere.

    These methods can be called using objects. Lets see how to call methods.
*/

class BoxDemo
{
    public static void main(String args[])
    {
        Box b = new Box();
        b.setDim(10,20,30); //Values are being passed into l,w and h.
        b.volume(); //Displays the volume of the box
    }
}

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

No comments:

Post a Comment