OOP Fundamentals
Classes and Objects
Building blocks of OOP
Classes and Objects form the conceptual foundation of Object-Oriented Programming (OOP). A class is a programmer-defined blueprint that specifies state variables and behavioral routines, whereas an object is a distinct instance allocated in memory that exhibits those states and executes those behaviors.
1. Learning Objectives
- Differentiate between Class blueprints and Object instantiations.
- Understand object allocation and reference assignment in runtime memory (Stack vs Heap).
- Trace the complete Lifecycle of an object from instantiation to garbage collection.
2. Problem Statement
In procedural programming, data and logic are separated. Global variables are modified by arbitrary functions, leading to mutable states that are difficult to trace. OOP addresses this by uniting data (attributes) and behavior (methods) inside a single entity, creating localized, controlled boundaries.
3. Real-world Analogy
Think of a blueprint of a house. The blueprint specifies the layout, window placement, and dimensions. It has no physical existence; you cannot live inside a blueprint.
The actual physical house constructed from that blueprint is the object. It occupies physical space, has actual paint colors, and you can live inside it. You can build thousands of distinct physical houses (objects) using the same blueprint (class).
4. Theory
A Class acts as a user-defined template. It defines:
- Attributes (Fields): Represent the state or characteristics of the object.
- Methods (Behaviors): Represent the operations or functions that the object can perform.
- Constructors: Special routines invoked during instantiation to initialize object fields.
5. Visual Diagrams (UML & Memory structures)
Class Diagram
Object Diagram
Illustrates two distinct instantiations containing local state values:
title = "Clean Code"
price = 45.00
title = "Design Patterns"
price = 55.00
Memory Diagram
Stack Frame (References)
Heap space (Object values)
Class Type: Book
sku: "SKU-909"
title: "Clean Code"
Object Lifecycle
6. Syntax Explanation
- Java: Declares classes with standard fields. Objects are instantiated via the
newkeyword. - Python: Declares initializer method
__init__representing the constructor block. Employsselfreference pointer for instance context. - C++: Classes can be instantiated on stack (
Book b;) or dynamically on heap usingstd::make_shared().
7. Step-by-Step Implementation
Let's build a clean, encapsulated Book Store Inventory Item class:
- Step 1: Declare the
Bookclass containing private propertiessku,title, andprice. - Step 2: Declare a public constructor to initialize all three properties.
- Step 3: Expose attributes using getters, adding parameter bounds checking inside the setters to protect class invariants.
- Step 4: Write main client method to verify reference swapping in memory.
8. Complete Code (Mini Project)
9. Code Walkthrough
In the code block above, book1 stores the reference address pointing to the clean code Book instance on the heap. We call .displayDetails() to print variables, while .setPrice(value) intercepts mutations to block invalid negative pricing.
10. Execution Flow
- Instantiate variables inside Stack frames.
- Trigger constructors to allocate properties on the heap.
- Invoke methods which process states and write formatted details to standard output.
11. Internal Working
Stack references are cleaned automatically when method execution exits. However, Heap object allocations remain active until no stack reference points to their address, at which point they are flagged for Garbage Collection.
12. Complexity Analysis
- Time Complexity: $O(1)$ to create instances and update member states.
- Space Complexity: $O(1)$ for storing distinct attributes in objects.
13. Best Practices
- Mark immutable variables as final: Helps with class thread-safety.
- Block null fields: Verify fields in constructors to keep objects in a valid state.
14. Common Mistakes
- Confusing local variable scope with class-level attributes.
- Forgetting to define a parameter constructor, which results in uninitialized null pointer fields.
15. Interview Questions
Q: What happens in memory when you assign Book b1 = b2?
Answer: The memory reference address of b2 is copied into b1. No new object is allocated on the heap; both b1 and b2 now point to the exact same object in memory.
16. Practice Exercises
- Easy: Add a
genrefield to the Book class. - Medium: Create a
StoreInventoryclass holding an array ofBookobjects. Expose a method to search books by title. - Hard: Implement a deep copy constructor for
StoreInventoryensuring modifications to copied inventory elements do not affect the original.
17. Challenge Problem
Design an encapsulated InventoryManager supporting concurrent access threads without causing thread collisions when updating stock levels.
18. Summary
- Classes are blueprints; Objects are distinct heap-allocated instances.
- References reside on Stack frames; actual object states reside in Heap space.
- Object attributes are private by default, and mutations go through getters/setters.
19. Cheat Sheet
| Term | Definition | Memory Allocation |
|---|---|---|
| Class | Static structural blueprint | Method Area (Metaspace) |
| Object | Dynamic instance holding values | Heap Area |
| Reference | Pointer containing object's address | JVM Stack Frame |
20. Quiz
1. Which of the following is true about a class?
A) It occupies space on the heap at runtime
B) It is a static blueprint or template that defines properties and behaviors (Correct)
C) It can only have one object instance in memory
2. Where are actual objects allocated in JVM memory layout?
A) Stack Area
B) Heap Area (Correct)
C) PC Registers
3. What is the scope of variables declared inside stack frames?
A) Global scope across all threads
B) Local scope limited to the active method call execution (Correct)
C) Shared across heap contexts
4. What is a constructor used for?
A) To delete objects from heap
B) To initialize an object's instance fields during creation (Correct)
C) To speed up compilation checks
5. If you set book1 = null, what happens to the Book object in memory?
A) It is deleted immediately
B) It becomes eligible for garbage collection if no other references point to it (Correct)
C) It causes a stack overflow error
6. What is the default access level of fields in Java if no modifier is set?
A) Private
B) Package-Private (Correct)
C) Protected
7. What is composition in OOP class design?
A) An "Is-A" inheritance link
B) A "Has-A" relationship where the child object's lifecycle is bound to the parent (Correct)
C) Implementing multiple interfaces simultaneously
8. Which operator triggers instantiation in Java?
A) static
B) new (Correct)
C) this
9. In C++, how are stack objects automatically deleted?
A) By calling free()
B) When execution leaves their local scope bracket (Correct)
C) By the garbage collector
10. What keyword refers to the active object instance context in Java/C++?
A) super
B) this (Correct)
C) self
21. Next Lesson Preview
In the next lesson, we will explore Enums to understand how to design type-safe constant selections with custom methods and attributes!