Course Content‎ > ‎Session 4‎ > ‎

Objects and Classes

Java is a true object-oriented programming language and therefore the underlying structure of all Java programs is classes. Anything we wish to represent in a Java program must be encapsulated in a class that defines the state and behavior of the basic program components known as objects. Classes provide a convenient way for packing together a group of logically related data items and functions that work on them. In Java, data items are called as fields and the functions are called as methods. Before we go through the concepts of objects and classes in detail, given below is the code of a simple program, which accepts the length and width and computes the area of the rectangle (this program has been discussed above also).
    class Rectangle     // Declaration of class Rectangle
        // Declaration of variables   
        int length,width; 
        // Definition of method setData 
        void setData(int x, int y) 
            length = x;
            width = y;
        // Definition of method rectArea
        int rectArea( )       
            int area; 
            area = length * width;
            return area;
    } // definition of class Rectangle ends here
    // class RectArea contains the main( ) method
    class RectArea      
        public static void main(String args[])
            int area1, area2; 
            // rect1 and rect2 are declared as objects of class Rectangle 
            Rectangle rect1, rect2;     
            // rect1 object is created  
            rect1 = new Rectangle( );
            // rect2 object is created  
            rect2 = new Rectangle( ); 
            /* accessing the variable length of the object rect1 and 
               assigning value to it  */
            rect1.length = 15;        
            /* accessing the variable width of the object rect1 and 
               assigning value to it */
            rect1.width = 10; 
            // calculating the area1  
            area1 = rect1.length * rect1.width;
            /* accessing the method setData( ) to assign the values to the
               instance variables length and width of rect2 */ 
            rect2.setData(20, 12);  
            // calculating the area2 by accessing the method rectArea
            area2 = rect2.rectArea();  
            System.out.println("Area1 = " + area1);
            System.out.println("Area2 = " + area2);  
    } // definition of class RectArea ends here
    Program output:
    Area1 = 150
    Area2 = 240
The name of the java file for this java program will be as it is the class RectArea that contains the main( ) method.
Creating Classes
Defining a class
A class is a user-defined data type that packs together a group of logically related data items and methods that work on these data items. Once a class has been defined, we can create variables of that type using declarations that are similar to the basic type declarations. In Java these variables are termed as instances of classes i.e. objects. Class serves as a template for making objects. The basic form of class definition is:
    class classname  [extends superclassname]
        [variable declaration; ]
        [methods declaration; ]

classname and superclassname are any valid Java identifiers. extends is a keyword, which indicates that the properties of superclassname class are extended to the classname class.  This concept is called as inheritance.
NOTE: Everything inside the square brackets i.e. [ ] is optional.
    class a1   // this is a valid class definition
In this class a1, the body is empty. This means class a1 does not contain any properties and therefore cannot do anything.  But we can compile it and even create objects using it.
Adding variables to a class
Data is encapsulated in a class by placing data fields inside the body of class definition.  These variables are called as instance variables because these variables are created whenever an object is instantiated. We can declare the instance variables exactly the same way as we declare local variables.  For example,
    class Rectangle
        /* length is an instance variable or member variable */   
        int length;  
        /* width is an instance variable or member variable */
        int width;

The class Rectangle contains two integer type instance variables. We can also declare the instance variables of same type in the same line. For example,
    class Rectangle
        int length, width;

These instance variables are declared, but they have not been allocated any storage space in the memory yet. 
Adding methods to a class
A class with only data items and no methods to operate on that data is not of much use. The objects created by such a class cannot respond to any messages. We must therefore add methods that are necessary for manipulating the data contained in the class. Methods are declared inside the body of the class but immediately after the declaration of instance variables. The general form of a method declaration is:
    type methodname (parameter list)
        method body;
Method declaration has four basic parts:
1. The name of the method (methodname)
methodname is a valid identifier.

2. The type of the value the method returns (type)
type specifies the type of the value the method would return. This could be a simple data type such as an int or a user-defined type i.e. a class. It could be of type void, if the method does not return any value.

3. A list of parameters (parameter list)
Parameter list is always enclosed in parentheses.  this list contains variable names and types of all the values we want to give to the method as input. The variables in the parameter list are separated by commas. In case, there are no parameters that have to be passed to the method, the declaration must retain the empty parentheses.

4. The body of the method.
Method body describes the operations to be performed on the data.
Given below are some examples of method declaration:
    int Area(int length, int width)
    int Average()
    void Display()
    void setData(int x, int  y)

Given below are some examples of invalid method declaration:
    int Area(int length, width)
    void Display(void)

Let us consider an example of class Rectangle:

    class Rectangle
        /* length and width are the data members of class Rectangle */   
        int length, width;   
        /* setData is a method of class Rectangle */
        void setData(int x, int y); 
            /*value of x is assigned to data member length */  
            length = x;
            /* value of y is assigned to data member width */  
            width = y; 
        // rectArea is a method of class Rectangle, computes the area of rectangle  
        int rectArea() 
            int area = length * width;
            /*value of area is returned by rectArea method */   
            return area;  
The class Rectangle contains two instance variables: length and width both of type int. The class Rectangle also contains two methods. These two methods are:
setData() and rectArea()
In the setData() method, two integer values are passed which are then assigned to the instance variables length and width. The method setData() is added to provide values to the instance variables i.e. length and width because the instance variables cannot be accessed directly but can be accessed only inside the methods of the class Rectangle. As the setData() method does not return any value, this method has a return type of void. The method rectArea() computes area of the rectangle and returns the result i.e. area of the rectangle. Since the area would be an integer, the return type of the method has been specified as int. The parameter list of rectArea() method is empty.
Creating Objects
An object in Java is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object. Objects in Java are created using the new operator. The new operator creates an object of the specified class and returns a reference to that object. To create an object of type Rectangle:
    // rect1 is declared as an object of class Rectangle
    Rectangle rect1;  
    // object rect1 is created or instantiated using new operator. 
    rect1 = new Rectangle( );
    // object rect2 is created or instantiated using new operator  
    rect2 = new Rectangle( );

The statement Rectangle rect1; declares a variable rect1 of type Rectangle to hold the object reference and the statement rect1 = new Rectangle( ); assigns the object reference to rect1. rect1 is now an object of class Rectangle. We can combine both the statements into a single statement: Rectangle rect1 = new Rectangle( ); The method Rectangle( ) is the default constructor (described later in this session) of class Rectangle.

We can create any number of objects of class Rectangle. For example,
    Rectangle rect1 = new Rectangle( );
    Rectangle rect2 = new Rectangle( );

and so on.

Each object has its own copy of the instance variables of its class. This means any changes to the instance variables of one object will have no effect on the instance variables of another object. It is also possible to create two or more references to the same object as given below:

    Rectangle r1 = new Rectangle();  
    // assigning one object reference variable to another
    Rectangle r2 = r1; 

Now both r1 and r2 refer to the same object.
Accessing class members
When the object has been created, each object contains its own set of instance variables. In order to use these variables in the program, we have to assign values to these variables. We cannot access the instance variables and methods directly outside the class. For this, we have to use the object of that class and the dot operator. The syntax for how an object is used to access the instance variable or a method is given below:
    //to access the instance variable
    objectname.variable name;  
    //to access the instance method
    objectname.methodname(parameter list);

  • objectname is the name of the object
  • variablename is the name of the instance variable inside the object that we wish to access
  • methodname is the method that we wish to call
  • parameter list is a comma separated list of actual values or expressions that must match in type, number and order with the parameter list of the methodname declared in the class.
For example, the instance variables of class Rectangle may be accessed and assigned values as follows:
    // the variables of rect1 have been instantiated
    rect1.length = 15; 
    rect1.width = 10;

But we can also assign the values to the instance variables length and width by calling setData method as shown below:
    // the variables of rect2 have been instantiated by using setData( ) method 

This statement passes in the values 20 and 12  for x and y parameters of the method setData. The method setData is shown below:
    void setData(int x, int y)
        // now the instance variable length is assigned the value contained in x   
        length = x;   
        //  now the instance variable width is assigned the value contained in y 
        width = y;     
Now the objects rect1 and rect2 contain the values for its variables, now we can compute the area of the rectangle represented by rect1 and rect2. The integer variable area1 will be assigned the area of the rectangle represented by object rect1.
    // calculating the area1  
    area1 = rect1.length*rect1.width; 

The integer variable area2 will be assigned the area of the rectangle represented by object rect2. For this rectArea( ) method has been called. The integer value returned by the method rectArea( ) is assigned to the variable area2.
    // calculating the area2 by accessing the method rectArea

Subpages (1): Methods (Advanced)