Showing posts with label Lab. Show all posts
Showing posts with label Lab. Show all posts

Tuesday, 20 December 2011

07 - this keyword

//Demonstrating the use of "this" keyword.

/*
    When the parameter names in a method are equal the names of the instance variables,
    the paramters will hide the instance variables. This concept is known as instance
    variables hiding.

    Lets see the following piece of code:

    class Box
    {
        int length;
        int width;
        int height;
   
        Box(int length,int width,int height)
        {
            length = length;
            width = width;
            height = height;
        }
    }

    If you look at the Box constructor above, the names of the three parameters and the
    names of the instance variables are same. So, this is an ambiguous situation.

    To eliminate this kind of situation we use the "this" keyword.
    "this" always refers to the current object.

    Lets see how to elimiate the ambiguity in the above piece of code...
*/

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

    Box(int length,int width,int height)
    {
        this.length = length;
        this.width = width;
        this.height = height;
    }

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

class BoxDemo
{
    public static void main(String args[])
    {
        Box b1 = new Box(10,20,30);
        b1.volume();
    }
}

//Remove all the "this" keywords in the above program and observe the output.

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

06 - Passing objects as parameters

//Program to demonstrate passing objects as parameters

/*
    In java, as we are able to pass primitive type values like int, float, double etc,
    we can also pass an entire object as a parameter to an object.

    This is done as shown in the following program:
*/

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

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

    boolean chkBox(Box b)
    {
        if((length == b.length) && (width == b.width) && (height == b.height))
        return true;
        else
        return false;
    }
}

/*
    In the above code chkBox() method checks whether two objects are having the same dimensions
    or not. If they are same, the method returns "true" or if they are different, it returns
    "false". That is why I have declared the return type as "boolean".

    Since I will be passing a Box object as a parameter, I have to receive it with the same type
    of variable. That is why I had declared "Box b". Here "b" will be referencing or pointing to
    the object passed in the calling function.
*/

class BoxDemo
{
    public static void main(String args[])
    {
        Box b1 = new Box(10,20,30);
        Box b2 = new Box(10,20,30);
        System.out.println("b1 and b2 are same: "+b1.chkBox(b2)); //Object b2 is passed as a parameter here.
        Box b3 = new Box(20,40,60);
        System.out.println("b1 and b3 are same: "+b1.chkBox(b3)); //Object b3 is passed as a parameter here.
    }
}

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

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

04 - Scope and lifetime of variables

//Demostrating the scope of variables (local variables)

/*
    In java anything present in between { and } is treated as a block. For example:
   
    {
        Set of statements;
    }

    The above is a block. Also,

    if(condition)
    {
        Set of statements;
    }

    is also a block.

    So, now lets discuss about variables. In java there are four types of variables:
    1) Instance variables: Non-static variables declared inside a class.
    2) Class variables: Static variables declared inside a class.
    3) local variables: Variables declared within methods and within blocks.
    4) Parameters: These are also a type of local variables with respect to the method.

    Now, lets discuss about the scope of local variables:
    The scope of all the local variables and parameters is within the block in which they are declared.
    They cannot be accessed outside the block in which they are declared.

    Lets see this in the following example:
*/

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

    void setDim(int l,int w,int h)
    {
        length = l;
        width = w;
        height = h;
    }
   
    void volume()
    {
        if(length!=0 && width!=0  && height!=0)
        {
            int vol = length*width*height;
            System.out.println("Volume of the Box is: "+vol);
        }
        //System.out.println("Volume of the Box is: "+vol);
    }
}

/*
    In the above code, if you see the volume() method, the "vol" variable is a local variable
    with respect to the "if" block. So, the scope of the "vol" variable is within the "if" block
    only. It cannot be accessed outside the "if" block.

    That is why the print statement after the "if" block is commented. If you remove the comments
    and excute the program, you will get an error. Try it!
*/

class BoxDemo
{
    public static void main(String args[])
    {
        Box b = new Box();
        b.setDim(10,20,30);
        b.volume();
    }
}

Downloading the program only: http://paste2.org/followup/1832512

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

02 - Computing volume of Box

//Computing the volume of a Box.

/*
    In the previous program we have seen how to declare a class and object.
   
    Lets compute the voulme of the box. Volume = length*width*height.

    One way of computing the voulme is as shown below:
*/

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

class BoxDemo
{
    public static void main(String args[])
    {
        Box b = new Box();
        b.length = 10;
        b.width = 20;
        b.height = 30;

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

/*
    In the above program "volume" is a local variable with respect to main function.
    So, "volume" can be accessed directly without creating any object.
*/

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

01 - Classes and Objects

Lets learn about classes and objects:

//Program to demonstrate the concept of Classes and Objects

/*
    A class is a template or blueprint for all the objects.
    A class specifies the behavior(methods) common to all objects.
    An object is an instance of a class.

    Syntax for declaring a class:
    class ClassName
    {
        data-type instance-variable1;
        data-type instance-variable2;
        ...
        return-type methodName1()
        {
            Statements;
        }
        return-type methodName2()
        {
            Statements;
        }
        ...
    }

    In the above syntax, "class" is a keyword used to declare a class in java.
    In java, the class names follow a certain convention/notation which is as follows:
    Every first letter in each word must be a captial/uppercase letter. In the syntax above, ClassName consists of
    two words, class and name. So, the first letters in each word i.e "C" in class and "N" in name must be written
    in uppercase.

    In a class the variables(non-static) are called as instance variables.
    In a class the instance variables along with methods collectively are called as class members.

    A class can contain only instance variables or only methods or a combination of methods.

    Syntax for declaring an object:
    ClassName object-identifier = new ClassName();

    object-identifier can be any valid identifier in java.

    Generally in java all the computations are performed using objects only.

    Lets see an example of declaring a class and an object.
*/

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

/*
    In the above code I have declared a class whose name is "Box".
    Box class contains three instance variables length, width and height.
    These variables can be accessed using an object of "Box" class.

    Generally in java programs, logic and execution statements are written in separate classes.
    Lets declare a "BoxDemo" class and create an object for our "Box" class.

    Members of a class can be accessed using an object using the following syntax:
    object.membername;
*/

class BoxDemo
{
    public static void main(String args[])
    {
        Box b = new Box();
        b.length = 10;
        b.width = 20;
        b.height = 30;
        System.out.println("Box length is: "+b.length);
        System.out.println("Box width is: "+b.width);
        System.out.println("Box height is: "+b.height);
    }
}

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