Tuesday, 20 December 2011

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

No comments:

Post a Comment