BCA / B.Tech 9 min read

Class & Object in Java

Class and Object in Java

Class and Object are the foundational pillars of Object-Oriented Programming (OOP). Understanding their relationship is key to writing Java programs.

Analogy: Blueprint and Houses

Think of a class as an architect's blueprint for a house. The blueprint defines all the properties (e.g., number of rooms, color of walls) and behaviors (e.g., open door, switch on lights) a house can have. The blueprint itself is just a plan; you can't live in it.

An object is an actual house built from that blueprint. It is a real, tangible entity that exists in the world (or in memory). You can build many houses (objects) from the same blueprint (class), and each house will be a unique instance with its own specific properties (e.g., one house is red, another is blue).


1. Class: The Blueprint
  • A class is a template or user-defined data type.
  • It defines a set of attributes (fields or variables) and behaviors (methods).
  • It is a logical entity; it does not occupy memory space until an object is created from it.

// This is the blueprint for a Dog
class Dog {
    // Attributes (state)
    String name;
    String breed;

    // Behavior (methods)
    void bark() {
        System.out.println("Woof!");
    }
    void wagTail() {
        System.out.println(name + " is wagging its tail.");
    }
}
        
2. Object: The Instance
  • An object is an instance of a class.
  • It is a physical entity that has state (values for its attributes) and behavior (defined by its class methods).
  • When an object is created using the new keyword, memory is allocated for it on the heap.

public class Main {
    public static void main(String[] args) {
        // Create two Dog objects (two houses from the blueprint)
        Dog dog1 = new Dog();
        dog1.name = "Buddy";
        dog1.breed = "Golden Retriever";
        
        Dog dog2 = new Dog();
        dog2.name = "Lucy";
        dog2.breed = "Poodle";

        // Call their methods
        dog1.wagTail(); // Outputs "Buddy is wagging its tail."
        dog2.wagTail(); // Outputs "Lucy is wagging its tail."
    }
}