Java Classes and Objects

Class

A class forms the basis for object-oriented programming. It defines the shape and nature of the object.

Any concept that we want to implement in oop’s must be encapsulated within a class. A class is a template for an object and an object is an instance for a class.

In another words class is a user defined data type.

Object

An object is a run time entity which has state and behavior. Example: A dog has states – name, breed ,color, etc. and behaviors – barking, eating etc.

It is a basic unit of Object Oriented Programming and represents the real-life entities. In a java program, we can create many objects and it is an instance of a class.

How to create object

Syntex for object:   

 
 ClassName   ObjectName  =   new   ClassName();   

new operator dynamically allocates  memory for an object

Write a program to demonstrate class and variables.

 
class RectangleArea {

    int length;
    int width;
}

public class Area {

    public static void main(String arg[]) {
        RectangleArea obj1 = new RectangleArea();
        RectangleArea obj2 = new RectangleArea();
        int a;
        // assign value to obj1 instance variable
        obj1.length = 10;
        obj1.width = 20;
        // assign value to obj2 instance variable 
        obj2.length = 10;
        obj2.width = 30;
        a = obj1.length * obj1.width;
        System.out.println("Area of the rectangle =" + a);
        a = obj2.length * obj2.width;
        System.out.println("Area of the rectangle =" + a);
    }
}


Result

Area of the rectangle =200
Area of the rectangle =300

In above program we can create an object in two lines as.                                                    

 
RectangleArea    obj1;
obj1  =  new   RectangleArea ();
   

 First line declares the obj1 as a reference to an object. After this line obj1 contains a null value. Any attempt to  use obj1 at this point will result in compile time error.

Next line allocates a RectangleArea  object.