Class & object in Java

A class is often defined as the blueprint or template for an object. We can create multiple objects from a class.

An object is an identifiable entity with some characteristics, state and behaviour.

Memory is allocated when we create the objects of a class type. A class contains properties and methods to define the state and behaviour of its object. It defines the data and the methods that act upon that data.

Example :
   A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.

Syntax Of Class :
   class class_name
        Variables ;
        Methods ;

Syntax Of Object :
   Class_Name ReferenceVariable ( or ) Object = new Class_Name ( ) ;

This Java program demonstrates the usage of a class and objects to calculate the area of a rectangle. The program defines a class Rectangle, which has two instance variables length and width, and two methods getDetails and area. The getDetails method is used to set the values of length and width of a rectangle object. It takes two integer arguments x and y, representing the length and width of the rectangle, respectively.

The area method calculates the area of a rectangle using the length and width instance variables and returns the result. In the main method, two rectangle objects o1 and o2 are created using the Rectangle class.

For o1, the length and width instance variables are set using direct assignment statements. The area method is then called on o1 to calculate and print the area of the rectangle.

For o2, the getDetails method is called with the arguments 20 and 30 to set the length and width instance variables. The area method is then called on o2 to calculate and print the area of the rectangle.

Source Code

//Class & Object in Java
class Rectangle
    int length, width;
    void getDetails(int x, int y) {
        length = x;
        width = y;
    int area() {
        int a = length * width;
        return a;
public class class_object {
    public static void main(String args[]) {
        Rectangle o1 =new Rectangle();
        System.out.println("Area of Rectangle : "+o1.area());
        Rectangle o2=new Rectangle();
        System.out.println("Area of Rectangle : "+o2.area());


Area of Rectangle : 200
Area of Rectangle : 600
To download raw file Click Here

Basic Programs