Class and Object in Java
Class
A class is like a blueprint or template used to create objects.
It defines properties (variables) and behaviors (methods).
It does not occupy memory until objects are created.
Example:
class Car {
String color; // property
int speed; // property
void drive() { // method
[Link]("Car is driving");
}
}
Object
An object is an instance of a class.
It represents a real-world entity.
It contains actual values and can use methods defined in the class.
Memory is allocated when an object is created.
Example:
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // object creation
[Link] = "Red";
[Link] = 120;
[Link](); // calling method
}
}
Memory Allocation in Java
Java uses mainly 2 types of memory:
🧠 1. Stack Memory
Stores reference variables
Example: myCar
🧠 2. Heap Memory
Stores actual objects
Example: Car object with data
How Memory Works (Step-by-Step)
Step 1: Object Creation
Car myCar = new Car();
🧠 Memory Diagram:
Stack Heap
----- -----
myCar -----------> Car Object
color → null
speed → 0
👉 Explanation:
myCar → stored in stack
Actual object → stored in heap
Default values:
o color = null
o speed = 0
Assigning Values
[Link] = "Red";
[Link] = 120;
🧠 Memory Now:
Stack Heap
----- -----
myCar -----------> Car Object
color → "Red"
speed → 120
Multiple Objects
Car car1 = new Car();
Car car2 = new Car();
🧠 Memory:
Stack Heap
----- -----
car1 -----------> Car Object 1
color → null
speed → 0
car2 -----------> Car Object 2
color → null
speed → 0
👉 Each object has separate memory
Where are Methods Stored?
void drive() {
[Link]("Car is driving");
}
Methods are stored in a special area called:
Method Area (Metaspace)
Method Area:
[Link]
drive() method (only one copy)
✔ Shared by all objects
✔ Not duplicated
Memory Summary Table
Component Stored In
Object Heap
Reference variable Stack
Methods Method Area
Static variables Method Area
Simple Real-Life Analogy
Concept Example
Class Blueprint of a house
Object Actual house
Stack Address of house
Heap Real house
Key Points
✔ Class = Blueprint
✔ Object = Real instance
✔ Stack = Reference (address)
✔ Heap = Actual object
✔ Methods = Stored once
✔ Each object = Separate memory