Introduction to OOP: Classes vs Objects
Welcome to Object-Oriented Programming (OOP) in Java! 🚀
So far in this masterclass, you have learned:
- How Java source code compiles to bytecode and runs on the JVM
- Primitive variables (
int,double,boolean) and their fixed bit sizes - How Stack memory handles method call frames and local variables
- How Heap memory dynamically manages allocated objects
- How to dry-run programs step-by-step
Now, we make the single biggest conceptual leap in your programming journey: transitioning from procedural instructions to Object-Oriented Programming (OOP).
Nearly everything in professional Java is built around classes and objects. Once you truly understand how objects live in memory, OOP stops being confusing and becomes your most powerful programming tool.
1. What Is Object-Oriented Programming?
In procedural programming, code is just a sequence of instructions executing top-to-bottom.
In Object-Oriented Programming (OOP), we organize software around real-world entities called Objects.
Look around your room right now. What do you see?
- A Laptop
- A Smartphone
- A Water Bottle
- A Pet Dog
- A Student
Every real-world entity has two things:
- State (Properties / Data): What the object has or knows.
- Behavior (Actions / Functions): What the object does.
Let's break down two examples:
| Entity | State (Fields / Data) | Behavior (Methods / Actions) |
|---|---|---|
| 🚗 Car | Brand (Toyota), Color (Red), Current Speed (60) | startEngine(), accelerate(), applyBrakes() |
| 🐕 Dog | Name (Buddy), Breed (Golden Retriever), Age (3) | bark(), eat(), sleep() |
| 💳 BankAccount | AccountNumber (10248), Owner (Aarav), Balance (5400.00) | deposit(), withdraw(), checkBalance() |
In Java, we represent State using Fields (Variables), and we represent Behavior using Methods (Functions).
2. Class vs Object: The Golden Analogy
This is the most critical distinction in all of software engineering:
A Class is the Blueprint.
An Object is the Actual Physical Thing built from that blueprint.
The Architect's Blueprint 📐
Imagine an architect draws a detailed blueprint for a 3-bedroom house.
- Can you live inside the blueprint? No! It is just ink on paper. It takes up no physical land.
- Can you construct 50 identical houses across a neighborhood from that single blueprint? Yes!
- Can House #1 be painted yellow, while House #2 is painted blue? Yes! Each house is built from the same blueprint, but each maintains its own independent state.
Class (Blueprint on Paper)
│
┌───────────┼───────────┐
▼ ▼ ▼
House #1 House #2 House #3
(Object) (Object) (Object)
Color: Blue Color: Red Color: Green
The Cookie Cutter Analogy 🍪
- The Cookie Cutter is the Class. It defines the shape, height, and border.
- The Cookies made of dough are the Objects. You can put chocolate chips on one cookie and sprinkles on another, but they all share the exact same structural shape.
3. Writing Your First Class
Let's write a Car class in Java:
// Blueprint definitionclass Car { // 1. Fields (State / Properties) String brand; String color; int speed; // 2. Methods (Behavior / Actions) void startEngine() { System.out.println(brand + " engine started: Vroom vroom!"); } void accelerate(int increase) { speed += increase; System.out.println(brand + " accelerated to " + speed + " km/h"); } void applyBrakes() { speed = 0; System.out.println(brand + " has come to a complete stop."); }}Notice:
String brand;,String color;, andint speed;are instance variables (fields). Every car object will get its own set of these fields.startEngine(),accelerate(), andapplyBrakes()are instance methods. They describe what a car object knows how to do.
4. Instantiating Objects with the new Keyword
Having the Car class definition does not create any car in computer memory yet. To bring an actual object to life, we must instantiate it using the new operator:
Car myCar = new Car();Let's dissect this single line of code piece by piece:
Car myCar = new Car();
───── ─────── ───────────
│ │ │
Data Type Reference Variable Creates actual object
(Class type) (Stored on STACK) (Allocated on HEAP)
Car: Specifies the type of the reference variable.myCar: The variable name. This variable lives on the Stack and holds the memory address of the object.new: Tells the JVM: "Allocate fresh memory on the Heap right now!"Car(): Calls the class constructor to initialize the newly created object.
Accessing Fields and Methods with the Dot (.) Operator
Once we hold a reference to an object, we use the dot operator . to read or modify its fields and call its methods:
public class Main { public static void main(String[] args) { // Create an object Car myCar = new Car(); // Set properties using dot notation myCar.brand = "Toyota"; myCar.color = "Crimson Red"; myCar.speed = 0; // Call behaviors using dot notation myCar.startEngine(); myCar.accelerate(45); myCar.applyBrakes(); }}Console Output:
Toyota engine started: Vroom vroom!
Toyota accelerated to 45 km/h
Toyota has come to a complete stop.
5. Under the Hood: Stack vs Heap Memory Diagrams
Let's look at exactly what happens inside computer memory when you create multiple objects:
public class Main { public static void main(String[] args) { Car car1 = new Car(); car1.brand = "Tesla"; car1.speed = 80; Car car2 = new Car(); car2.brand = "Honda"; car2.speed = 50; }}🧠 Physical Memory Layout:
STACK MEMORY HEAP MEMORY
(Fast, method frames, local vars) (Dynamic object storage)
┌───────────────────────────────┐ ┌───────────────────────────────────────┐
│ main() frame: │ │ Address: @0x100 │
│ │ │ ┌───────────────────────────────────┐ │
│ car1 = @0x100 ────────────────┼──────────►│ │ Car Object #1 │ │
│ │ │ │ brand = "Tesla" │ │
│ │ │ │ speed = 80 │ │
│ │ │ └───────────────────────────────────┘ │
│ │ │ │
│ │ │ Address: @0x200 │
│ │ │ ┌───────────────────────────────────┐ │
│ car2 = @0x200 ────────────────┼──────────►│ │ Car Object #2 │ │
│ │ │ │ brand = "Honda" │ │
│ │ │ │ speed = 50 │ │
│ │ │ └───────────────────────────────────┘ │
└───────────────────────────────┘ └───────────────────────────────────────┘
Critical Takeaways:
car1andcar2are independent. Modifyingcar1.speed = 120;only alters the object at memory address@0x100. The object at@0x200remains completely untouched.- The variables
car1andcar2do not hold the car data itself. They hold remote control pointers (references) pointing to the objects on the Heap.
6. Reference Copying vs Object Copying (Aliasing)
What happens when you assign one object reference variable to another?
Car carA = new Car();carA.brand = "Ferrari";carA.speed = 200;// Look closely at this line:Car carB = carA;// Now let's change carB:carB.speed = 300;// What does carA print?System.out.println("carA speed: " + carA.speed);Output:
carA speed: 300
❓ Why did carA.speed change when we modified carB?
Beginners often assume Car carB = carA; creates a brand-new copy of the car. It does not!
It only copies the reference (the address pointer):
STACK HEAP
┌───────────┐ ┌───────────────────┐
│ carA: @100│ ───────────────┐ │ Object at @100: │
├───────────┤ ├───────► │ brand = "Ferrari" │
│ carB: @100│ ───────────────┘ │ speed = 300 │
└───────────┘ └───────────────────┘
Both carA and carB are pointing to the exact same object in Heap memory!
- Think of it like two TV remote controls synced to the same television.
- If you use Remote B to change the volume to 50, looking at the TV through Remote A shows the volume is now 50!
- This phenomenon is called Object Aliasing.
7. The Dreaded null and NullPointerException
In Java, if a reference variable is declared but not assigned to any object, or explicitly assigned null, it points to nothing:
Car myCar = null; STACK HEAP
┌───────────┐
│ myCar: null│ ───► [Points to nowhere / unmapped address 0x0]
└───────────┘
What happens if you try to use the dot operator . on a reference that is null?
Car myCar = null;myCar.startEngine(); // 💥 CRASH!Console Error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Car.startEngine()" because "myCar" is null
Why does this happen?
The dot operator means: "Go to the address this variable points to, and access its member."
If myCar holds null, there is no object on the Heap to go to! The JVM halts execution and throws NullPointerException (often called NPE).
How to guard against it:
Always verify that a reference is non-null before invoking methods if there is a chance it wasn't initialized:
if (myCar != null) { myCar.startEngine();} else { System.out.println("Warning: Car object is not instantiated!");}8. Default Field Values in Java
When you allocate an object on the Heap with new, Java automatically initializes all instance fields to safe default values before your code runs:
| Data Type | Default Value | Example Field | Initialized Value |
|---|---|---|---|
int, byte, short | 0 | int age; | 0 |
long | 0L | long count; | 0L |
float, double | 0.0 | double price; | 0.0 |
boolean | false | boolean isActive; | false |
char | '\u0000' (null char) | char grade; | '\0' |
Any Object Reference (String, Car, etc.) | null | String name; | null |
⚠️ Contrast with Local Variables: Local variables inside a method (like
int x;insidemain) are never given default values. The Java compiler forces you to initialize local variables before reading them, or it refuses to compile. Instance fields inside an object on the Heap, however, are always initialized automatically.
9. Comprehensive Hands-On Code Example
Let's build a complete, runnable Java program that puts all these concepts together:
// File: StudentDemo.javaclass Student { // 1. Instance fields (State) String name; int rollNumber; double gpa; // 2. Instance methods (Behavior) void displayProfile() { System.out.println("---------------------------"); System.out.println("Student Name : " + name); System.out.println("Roll Number : " + rollNumber); System.out.println("Current GPA : " + gpa); } boolean isHonorRoll() { return gpa >= 3.8; }}public class Main { public static void main(String[] args) { // Instantiate first student Student s1 = new Student(); s1.name = "Ananya Sharma"; s1.rollNumber = 101; s1.gpa = 3.92; // Instantiate second student Student s2 = new Student(); s2.name = "Rohan Verma"; s2.rollNumber = 102; s2.gpa = 3.45; // Invoke behaviors s1.displayProfile(); System.out.println("Honor Roll Eligible: " + s1.isHonorRoll()); s2.displayProfile(); System.out.println("Honor Roll Eligible: " + s2.isHonorRoll()); // Demonstrating Aliasing Student s3 = s1; // s3 now points to s1's heap object s3.gpa = 4.00; // Mutating via s3 System.out.println("\nAfter updating s3.gpa to 4.00:"); System.out.println("s1's GPA is now: " + s1.gpa); // Also 4.0! }}Output:
---------------------------
Student Name : Ananya Sharma
Roll Number : 101
Current GPA : 3.92
Honor Roll Eligible: true
---------------------------
Student Name : Rohan Verma
Roll Number : 102
Current GPA : 3.45
Honor Roll Eligible: false
After updating s3.gpa to 4.00:
s1's GPA is now: 4.0
10. Summary Checklist for Beginners
Before moving to Constructors in the next lesson, ensure you understand:
- A Class is an abstract blueprint; an Object is an actual physical instance in memory.
- State is represented by Fields; Behavior is represented by Methods.
- The
newoperator allocates memory on the Heap. - Reference variables live on the Stack and store the address pointing to the Heap object.
Car b = a;copies the address, not the object itself (Object Aliasing).- Invoking methods on a
nullreference triggers a runtimeNullPointerException. - Heap instance fields receive safe default values (
0,false,null) automatically upon creation.